Mastering Go Middleware: From Basics to Advanced Patterns
This article explains what middleware is, why it’s used in Go projects, and demonstrates various implementations—including logging, authentication, method checks, and chaining—through clear code examples for both the standard net/http package and the Gin framework, helping developers enhance their backend services.
What is middleware? This article introduces the concept of middleware in Go projects, describing its purpose and effects.
Middleware is software that provides services to applications running on an operating system, facilitating communication between components, especially in web applications and service‑oriented architectures.
In Go, middleware is commonly used for:
Recording incoming requests
Processing server responses
Performing authentication between request and handling
Remote procedure calls
Security
Other cross‑cutting concerns
A middleware handler is a simple http.Handler that wraps another http.Handler to perform pre‑processing or post‑processing of a request. It sits between the Go web server and the actual handler.
Logging Middleware Example
package main
import (
"fmt"
"log"
"net/http"
)
func logging(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.Path)
f(w, r)
}
}
func foo(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "foo")
}
func bar(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "bar")
}
func main() {
http.HandleFunc("/foo", logging(foo))
http.HandleFunc("/bar", logging(bar))
http.ListenAndServe(":8080", nil)
}Accessing http://localhost:8080/foo returns foo. The same functionality can be expressed with a slightly different structure:
package main
import (
"fmt"
"log"
"net/http"
)
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.Path)
next.ServeHTTP(w, r)
})
}
func foo(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "foo") }
func bar(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "bar") }
func main() {
http.Handle("/foo", loggingMiddleware(http.HandlerFunc(foo)))
http.Handle("/bar", loggingMiddleware(http.HandlerFunc(bar)))
http.ListenAndServe(":8080", nil)
}Multiple Middleware Example
package main
import (
"fmt"
"log"
"net/http"
"time"
)
type Middleware func(http.HandlerFunc) http.HandlerFunc
// Logging logs request path and processing time
func Logging() Middleware {
return func(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
defer func() { log.Println(r.URL.Path, time.Since(start)) }()
f(w, r)
}
}
}
// Method ensures the request uses a specific HTTP method
func Method(m string) Middleware {
return func(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != m {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
f(w, r)
}
}
}
// Chain applies a list of middlewares to a handler
func Chain(f http.HandlerFunc, middlewares ...Middleware) http.HandlerFunc {
for _, m := range middlewares {
f = m(f)
}
return f
}
func Hello(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "hello world") }
func main() {
http.HandleFunc("/", Chain(Hello, Method("GET"), Logging()))
http.ListenAndServe(":8080", nil)
}Middleware essentially wraps an http.HandlerFunc and returns a new one, allowing multiple layers to be chained together.
Middleware in the Gin Framework
package main
import (
"github.com/gin-gonic/gin"
"log"
"time"
)
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
t := time.Now()
c.Set("example", "12345")
c.Next()
latency := time.Since(t)
log.Print(latency)
status := c.Writer.Status()
log.Println(status)
}
}
func main() {
r := gin.New()
r.Use(Logger())
r.GET("/test", func(c *gin.Context) {
example := c.MustGet("example").(string)
log.Println(example)
})
r.Run(":8080")
}The logger can also be attached directly to a route:
r.GET("/test", Logger(), func(c *gin.Context) { /* handler */ })For more Gin middleware examples, refer to the official Gin repository.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
