Building a REST API with Echo

Echo is a minimal, fast HTTP framework for Go. It gives you routing, middleware, and request binding without the ceremony of a full framework, which makes it a comfortable middle ground between the bare standard library and something heavier.

A minimal server

Every Echo app starts with an instance, a route, and a call to Start:

e := echo.New()
e.GET("/health", func(c echo.Context) error {
    return c.JSON(http.StatusOK, map[string]string{"status": "ok"})
})
e.Logger.Fatal(e.Start(":8080"))

Each handler receives an echo.Context that wraps the request and response, and returns an error. Returning an error lets Echo's centralized handler turn it into a clean HTTP response instead of scattering status codes through your code.

Bind and validate input

Echo binds JSON, form, and query data straight into a struct, so you stop hand-parsing request bodies:

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

func createUser(c echo.Context) error {
    var in CreateUser
    if err := c.Bind(&in); err != nil {
        return echo.NewHTTPError(http.StatusBadRequest, "invalid body")
    }
    // ... persist and respond
}

Middleware does the cross-cutting work

Logging, recovery from panics, CORS, and auth all belong in middleware so your handlers stay focused on business logic:

e.Use(middleware.Logger())
e.Use(middleware.Recover())

Group what shares concerns

Routes that share a prefix and a set of middleware - say, everything under /api/v1 behind auth - belong in a group. It keeps the route table readable and ensures you never forget to protect a new endpoint.

  • #go
  • #echo
  • #api
  • #rest