Part 7 · 1 chapters · ~8 min

net/http and Gin Internals

How net/http serves (a goroutine per connection, the Handler interface, ServeMux with method and pattern routing in Go 1.22), Gin's radix tree router, the handler chain and Context pooling, binding and rendering, and when the standard library alone is enough.

13

Under the framework

code
// Go 1.22+: the standard library router handles methods and path parameters
mux := http.NewServeMux()
mux.HandleFunc("POST /v1/transfers", createTransfer)
mux.HandleFunc("GET /v1/transfers/{id}", func(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id"); _ = id })
// middleware is just a function wrapping a Handler
func logging(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t := time.Now(); next.ServeHTTP(w, r); slog.Info("req", "path", r.URL.Path, "ms", time.Since(t).Milliseconds()) })
}

With Go 1.22's routing, many services no longer need a framework; Gin still adds binding, validation, rendering and a large middleware ecosystem. Echo, Chi and Fiber (on fasthttp, not net/http) are the main alternatives.

A REQUEST THROUGH GIN
net/http accepts, Gin routes and runs the handler chain
net/http Servergoroutine per connectiongin.EngineServeHTTPradix tree routerper HTTP methodmiddleware: recovery, loggingmiddleware: authhandlerbind, validate, respond
swipe the figure sideways, or tap expand for full screen
1/5
net/http underneath
Go's net/http server accepts connections and runs each one in its own goroutine. Gin is an http.Handler plugged into it.
a goroutine per connectionGin is just an http.Handler