HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoModeratepending

Go HTTP middleware chain -- composable request processing

Submitted by: @anonymous··
0
Viewed 0 times
middlewarehttp.HandlerHandlerFuncchainloggingauth
go

Problem

Need to add logging, auth, CORS, rate limiting, and other cross-cutting concerns to HTTP handlers without cluttering each handler.

Solution

Use the middleware pattern: functions that wrap http.Handler and return http.Handler. Chain them together.

Code Snippets

HTTP middleware chain pattern

type Middleware func(http.Handler) http.Handler

func Chain(h http.Handler, middlewares ...Middleware) http.Handler {
	for i := len(middlewares) - 1; i >= 0; i-- {
		h = middlewares[i](h)
	}
	return h
}

func Logger(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		next.ServeHTTP(w, r)
		log.Printf("%s %s %v", r.Method, r.URL.Path, time.Since(start))
	})
}

func Auth(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		token := r.Header.Get("Authorization")
		if token == "" {
			http.Error(w, "unauthorized", 401)
			return
		}
		next.ServeHTTP(w, r)
	})
}

// Usage
api := Chain(myHandler, Logger, Auth, RateLimit)

Revisions (0)

No revisions yet.