Skip to content
Tutorials Center
My learning

Topics

Lesson 116 of 147 ยท Web and Networking

Web Frameworks: Gin, Echo and chi

Compare Gin, Echo and chi with Go's standard net/http - routing groups, middleware, request binding and validation - and see runnable net/http stand-ins for each idea.

Go's standard library is unusually capable for web work. Since Go 1.22, http.ServeMux supports methods and path wildcards, so a plain net/http server can route GET /users/{id} without any dependency, as you saw in HTTP servers and handlers and middleware. Even so, many teams reach for a framework such as Gin, Echo or chi. This lesson explains what those add, how their code looks, and when the extra dependency is worth it.

The site's code runner has no network and no third-party packages, so Gin, Echo and chi code is shown in plain read-only blocks. Every idea also has a runnable stand-in written with net/http only, which uses the standard httptest package to call handlers without opening a port. Treat the framework snippets as accurate reference code, but check the current documentation for exact versions.

What a framework adds

A framework does not replace net/http; all three build on it. What they add is convenience around four things:

  1. Routing with groups and a nice syntax for parameters.
  2. Middleware chains with a standard way to stop or continue.
  3. Binding and validation: turning JSON, forms and query strings into structs and checking them.
  4. Helpers for rendering responses, serving static files and handling errors in one place.
net/http (1.22+) chi Gin Echo
Handler type http.Handler / func(w, r) http.Handler func(*gin.Context) func(echo.Context) error
Route groups via http.StripPrefix and sub-muxes r.Route, r.Group r.Group e.Group
Middleware functions wrapping a handler standard wrappers r.Use e.Use
Binding do it yourself do it yourself built in, validator tags built in, bring your own validator
Compatible with net/http handlers yes fully via adapters via adapters

The most important row is the first one. chi keeps the standard handler signature, so everything written for net/http works in it. Gin and Echo use their own context object, which gives richer helpers but ties your handlers to the framework.

Routing and groups

Here is the stand-in first. It registers a group of routes under /api/v1 with the standard mux, using a tiny helper to share the prefix.

Go Route groups with net/http only

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first line, //go:debug httpmuxgo121=0, switches on the method patterns for a single file compiled without a go.mod; inside a module that declares go 1.22 or newer, leave it out. The output shows 200 list users, 200 user 42, 201 created, then 405 for the unsupported DELETE (the standard mux answers with Method Not Allowed and a plain-text body) and 404 for /api/v2. Because a path that matches but with the wrong method gives 405 instead of 404, you get correct HTTP behavior for free.

The same routes in each framework:

Go
// chi
r := chi.NewRouter()
r.Route("/api/v1", func(r chi.Router) {
	r.Get("/users", listUsers)
	r.Get("/users/{id}", getUser) // chi.URLParam(r, "id")
	r.Post("/users", createUser)
})

// Gin
r := gin.Default() // includes Logger and Recovery middleware
v1 := r.Group("/api/v1")
{
	v1.GET("/users", listUsers)
	v1.GET("/users/:id", getUser) // c.Param("id")
	v1.POST("/users", createUser)
}

// Echo
e := echo.New()
v1 := e.Group("/api/v1")
v1.GET("/users", listUsers)
v1.GET("/users/:id", getUser) // c.Param("id")
v1.POST("/users", createUser)

Note the small differences in the parameter syntax: chi uses like the standard mux, Gin and Echo use :id. For nested groups, an extra middleware and a prefix are all a group has to carry.

Middleware

Middleware is code that runs before and after a handler: logging, authentication, panic recovery, timing. In net/http it is a function from handler to handler, which composes well. Here is a stand-in with two layers and a short-circuit:

Go A middleware chain with net/http

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

For the first request the log middleware runs, requireKey stops the chain, and the log shows status 401. For the second request the handler runs and the output reads status 200. The frameworks wrap the same idea:

Go
// chi: standard func(http.Handler) http.Handler
r.Use(middleware.Logger, middleware.Recoverer)

// Gin: handlers call c.Next() or c.Abort()
func requireKey() gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.GetHeader("X-Api-Key") != "secret" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "bad key"})
			return
		}
		c.Next()
	}
}
r.Use(gin.Logger(), requireKey())

// Echo: wraps a HandlerFunc that returns an error
func requireKey(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		if c.Request().Header.Get("X-Api-Key") != "secret" {
			return echo.NewHTTPError(http.StatusUnauthorized, "bad key")
		}
		return next(c)
	}
}
e.Use(middleware.Logger(), requireKey)

Echo handlers return an error, which a central error handler turns into a response; that removes many repeated if err != nil branches. Gin handlers return nothing and write to the context.

Binding and validation

Frameworks save time by decoding the request body into a struct and checking its fields in one call. Gin does it with struct tags:

Go
type CreateUser struct {
	Name  string `json:"name"  binding:"required,min=2"`
	Email string `json:"email" binding:"required,email"`
	Age   int    `json:"age"   binding:"gte=13,lte=130"`
}

func createUser(c *gin.Context) {
	var in CreateUser
	if err := c.ShouldBindJSON(&in); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusCreated, in)
}

Echo has c.Bind(&in) and expects you to plug in a validator such as go-playground/validator, which is the same library Gin uses internally. chi has no binding at all. With the standard library the equivalent is a small, explicit function. It is only a few more lines, and it lets you decide strictness:

Go Decoding and validating JSON with the standard library

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first body gives 201 and the echoed JSON. The second gives 422 with three lines of problems (one per failed rule, thanks to errors.Join). The third gives 400 bad JSON: json: unknown field "emial", and the last one a 400 with a syntax error message. Choosing 400 for malformed input and 422 for well-formed but invalid data is a common convention. Frameworks give you the declarative tag style; the standard library gives you total control.

Choosing: framework or standard library?

  • Start with net/http. The 1.22 mux is enough for most services, there is nothing to learn or upgrade, and handlers stay portable.
  • Add chi if you want groups, URL parameters on older Go versions or a rich set of ready-made middleware, but also want pure http.Handler code.
  • Pick Gin for fast JSON APIs when your team likes declarative binding and a large ecosystem of examples. It is the most popular choice.
  • Pick Echo if you prefer handlers that return errors, built-in static serving and a tidy central error handler.

Whichever you choose, keep business logic out of handlers. Handlers should translate HTTP into plain function calls on a service type, so the same code works in tests, in a command-line tool and under another framework, as described in clean architecture. A change of framework then touches only the thin outer layer.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these frameworks keeps the standard http.Handler signature?

    chi is built entirely on http.Handler and the standard Request and ResponseWriter. Gin and Echo define their own context type.
  2. 2. What does a middleware do to stop a request from reaching the handler?

    Short-circuiting means responding itself (for example with 401) and simply not calling the next handler in the chain.
  3. 3. In Echo, how does a handler report a failure to the central error handler?

    Echo handlers have the signature func(echo.Context) error. A returned error is turned into a response by the HTTPErrorHandler.
  4. 4. What does the standard ServeMux return when a path exists but the HTTP method is not registered?

    Go 1.22 method-aware patterns reply 405 with an Allow header when the path matches another method.

Summary

  • Gin, Echo and chi all build on net/http; they add routing groups, middleware chains, binding and response helpers.
  • chi stays compatible with http.Handler; Gin and Echo use their own context for richer helpers.
  • Middleware is a function that wraps a handler and may short-circuit; net/http composes it with plain functions.
  • Binding with struct tags is convenient; the standard library version (json.Decoder, DisallowUnknownFields, a Validate method) is explicit and equally testable.
  • Default to the standard library and add a framework when its conveniences clearly pay for the dependency; keep business logic out of handlers either way.

Next: Sending Email with net/smtp shows a different kind of network client.