Skip to content

HTTP services in Go with Echo — routing, middleware, and templating

Build a production Go HTTP service with the Echo framework — context wrapper, validator integration, middleware chains, graceful shutdown, and Prometheus metrics.

Echo is one of the most-used Go HTTP frameworks alongside chi and gin. It bundles routing, request binding, validation, templating, and middleware behind a single echo.Context abstraction — closer to a full-framework experience than chi’s “stdlib + extras” approach. This article shows the Echo layout Stack Harbor uses on teams that prefer a higher-level abstraction.

How to verify

A minimal Echo server boots and responds:

go get github.com/labstack/echo/v4 github.com/labstack/echo/v4/middleware
go run .
curl -i http://localhost:8080/healthz
curl -i -X POST -H 'Content-Type: application/json' -d '{"name":"Ana"}' http://localhost:8080/users

If the validator binding rejects an empty name with a 400 and accepts a valid one with a 201, the framework is doing the binding work for you.

What’s happening

Echo wraps net/http with its own request context (echo.Context) that carries the request, the response writer, path params, query params, the bound body, and trail state for middleware. Handlers return error instead of writing directly — Echo translates returned errors into HTTP responses through a centralized error handler.

The trade-off: handlers are not raw http.HandlerFunc, so middleware ported from chi or stdlib does not slot in directly. Echo’s middleware signature is func(echo.HandlerFunc) echo.HandlerFunc. This is a one-line adapter to/from stdlib if you need it.

Echo bundles ergonomic features that chi expects you to assemble: c.Bind(&dto) parses JSON/form/query into a struct using struct tags, c.Validate(&dto) runs go-playground/validator, c.Render("name", data) serves an HTML template, c.Stream(ContentType, reader) streams a response. For teams that want batteries included, Echo lowers the cognitive load.

The procedure

  1. Project structure.

    cmd/api/main.go
    internal/server/server.go
    internal/server/routes.go
    internal/handlers/users.go
    internal/models/user.go
  2. Bootstrap the server.

    package server
    
    import (
        "context"
        "errors"
        "net/http"
        "time"
    
        "github.com/labstack/echo/v4"
        "github.com/labstack/echo/v4/middleware"
        "log/slog"
    )
    
    type Server struct {
        e   *echo.Echo
        log *slog.Logger
    }
    
    func New(log *slog.Logger) *Server {
        e := echo.New()
        e.HideBanner = true
        e.HidePort = true
    
        e.Use(middleware.RequestID())
        e.Use(middleware.Recover())
        e.Use(slogMW(log))
        e.Use(middleware.Gzip())
        e.Use(middleware.TimeoutWithConfig(middleware.TimeoutConfig{
            Timeout: 15 * time.Second,
        }))
    
        e.Validator = newValidator()
        e.HTTPErrorHandler = errorHandler(log)
    
        e.GET("/healthz", func(c echo.Context) error {
            return c.NoContent(http.StatusOK)
        })
    
        return &Server{e: e, log: log}
    }
    
    func (s *Server) Run(ctx context.Context, addr string) error {
        errCh := make(chan error, 1)
        go func() {
            if err := s.e.Start(addr); err != nil && !errors.Is(err, http.ErrServerClosed) {
                errCh <- err
            }
        }()
        select {
        case <-ctx.Done():
            shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
            defer cancel()
            return s.e.Shutdown(shutdownCtx)
        case err := <-errCh:
            return err
        }
    }
  3. Register routes with groups.

    func (s *Server) RegisterRoutes() {
        api := s.e.Group("/api/v1", requireJWT())
        api.GET("/users/:id", handlers.GetUser)
        api.POST("/users", handlers.CreateUser)
        api.PUT("/users/:id", handlers.UpdateUser)
        api.DELETE("/users/:id", handlers.DeleteUser)
    
        hooks := s.e.Group("/webhooks", rateLimit(50))
        hooks.POST("/stripe", handlers.StripeWebhook)
    }

    Groups in Echo are the equivalent of chi subrouters — they propagate middleware to nested routes.

  4. Bind, validate, respond. A handler with struct-tag-driven validation:

    type CreateUserDTO struct {
        Name  string `json:"name" validate:"required,min=2,max=50"`
        Email string `json:"email" validate:"required,email"`
    }
    
    func CreateUser(c echo.Context) error {
        dto := new(CreateUserDTO)
        if err := c.Bind(dto); err != nil {
            return echo.NewHTTPError(http.StatusBadRequest, "invalid json")
        }
        if err := c.Validate(dto); err != nil {
            return echo.NewHTTPError(http.StatusBadRequest, err.Error())
        }
        u, err := store.CreateUser(c.Request().Context(), dto.Name, dto.Email)
        if err != nil {
            return fmt.Errorf("create user: %w", err)
        }
        return c.JSON(http.StatusCreated, u)
    }

    c.Bind reads body/headers/query based on Content-Type. Returned errors go through HTTPErrorHandler.

  5. Custom validator wiring.

    import (
        "github.com/go-playground/validator/v10"
        "github.com/labstack/echo/v4"
    )
    
    type customValidator struct{ v *validator.Validate }
    func (cv *customValidator) Validate(i interface{}) error { return cv.v.Struct(i) }
    func newValidator() echo.Validator { return &customValidator{v: validator.New()} }
  6. Centralized error handler. Translate domain errors to HTTP shapes:

    func errorHandler(log *slog.Logger) echo.HTTPErrorHandler {
        return func(err error, c echo.Context) {
            code := http.StatusInternalServerError
            msg := "internal error"
            if he, ok := err.(*echo.HTTPError); ok {
                code = he.Code
                msg = fmt.Sprintf("%v", he.Message)
            }
            if errors.Is(err, store.ErrNotFound) {
                code = http.StatusNotFound; msg = "not found"
            }
            log.Error("request failed", "err", err, "path", c.Path(), "method", c.Request().Method, "code", code)
            _ = c.JSON(code, map[string]string{"error": msg})
        }
    }
  7. Metrics via Prometheus. Echo has a middleware:

    import "github.com/labstack/echo-contrib/prometheus"
    
    p := prometheus.NewPrometheus("echo", nil)
    p.Use(e)

    That registers /metrics, populates per-route latency histograms, and exposes them to Prometheus.

Common pitfalls

  • c.Bind ignores unknown fields by default. Configure DisallowUnknownFields on the JSON binder if a typo in a request body should be an error.
  • echo.WrapMiddleware is required to adapt stdlib middleware. echo.WrapMiddleware(stdLibMW) wraps a func(http.Handler) http.Handler so Echo can use it.
  • c.Logger() is a separate logger from your slog. Either replace it (e.Logger = ...) or route everything through your own middleware that uses slog.
  • Path parameters use colons, not braces. e.GET("/users/:id", ...) — NOT /users/{id}. Easy gotcha when migrating from chi.
  • echo.NewHTTPError is the only way to set both code and message in one return. Otherwise the default error handler maps unknown errors to 500.

Stack Harbor stands up Echo-based services for teams that prefer a higher-level framework, and chi for teams that prefer stdlib-shaped routing. Both fit our managed operations practice — the operating model around them is identical.