Echo
01 / 02

Routing, Context & Binding

Routing, Context & Binding

Basic Server

package main

import (
  "net/http"
  "github.com/labstack/echo/v4"
)

func getUser(c echo.Context) error {
  id := c.Param("id")
  return c.JSON(http.StatusOK, map[string]string{"id": id})
}

func main() {
  e := echo.New()
  e.GET("/users/:id", getUser)
  e.Logger.Fatal(e.Start(":8080"))
}

Echo is a minimalist framework built on top of net/http, adding conveniences (routing, middleware, request/response helpers) without replacing Go's underlying HTTP handling. echo.Context is the per-request object every handler receives — access via c.Param("id") (path) vs. c.QueryParam("id") (query string) are distinct methods for distinct request parts.

Binding & Validation

type CreateUserRequest struct {
  Name  string `json:"name" validate:"required"`
  Email string `json:"email" validate:"required,email"`
}

func createUser(c echo.Context) error {
  req := new(CreateUserRequest)
  if err := c.Bind(req); err != nil {
    return err
  }
  if err := c.Validate(req); err != nil {
    return err
  }
  return c.JSON(http.StatusCreated, req)
}
// c.Validate requires registering a Validator implementation on echo.New()
// — Echo has no validator by default; go-playground/validator is common

Route Groups

api := e.Group("/api/v1")
api.Use(authMiddleware)   // applies to every route in this group
api.GET("/users/:id", getUser)
api.POST("/users", createUser)

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free