Senior
What is middleware in Go HTTP servers and how is it implemented?
sobes.tech AI
Answer from AI
Middleware in Go HTTP servers is a function or set of functions that wrap around the request handler (http.Handler) to add additional logic, such as logging, authentication, error handling, etc.
Middleware is implemented as a function that takes an http.Handler and returns an http.Handler. Example:
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Request: %s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r) // call the next handler
})
}
// Usage
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello"))
})
loggedMux := loggingMiddleware(mux)
http.ListenAndServe(":8080", loggedMux)
Thus, middleware allows sequential processing of requests, adding necessary functional layers without changing the main handler.