Middleware trong Go là một wrapper function nhận handler và trả về handler mới, cho phép chèn logic trước hoặc sau khi xử lý request.
go
// Middleware cơ bản — stdlib net/http
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if !isValidToken(token) {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r) // gọi handler tiếp theo
})
}
func loggingMiddleware(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))
})
}
// Chain middlewares — request đi từ ngoài vào trong
http.Handle("/api", loggingMiddleware(authMiddleware(apiHandler)))
// Gin middleware — đơn giản hơn
r := gin.Default()
r.Use(authMiddleware()) // áp dụng cho tất cả routes
api := r.Group("/api")
api.Use(rateLimitMiddleware()) // áp dụng cho groupMiddleware in Go is a wrapper function that receives a handler and returns a new handler, inserting logic before or after request processing.
go
// Basic middleware — stdlib net/http
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if !isValidToken(token) {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r) // call the next handler
})
}
func loggingMiddleware(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))
})
}
// Chain middlewares — request passes outside-in
http.Handle("/api", loggingMiddleware(authMiddleware(apiHandler)))
// Gin middleware — simpler registration
r := gin.Default()
r.Use(authMiddleware()) // applies to all routes
api := r.Group("/api")
api.Use(rateLimitMiddleware()) // applies to this group only