So, you’ve built a Go web server, but you need to add logging, authentication, or other functionalities to every request? That’s where middleware comes in! Middleware is like a bouncer at a club—it checks every request before letting it through.
What is Middleware?
Middleware is a function that wraps around your handlers to perform tasks before or after processing requests. Some common use cases include:
- Logging (recording requests and responses)
- Authentication (blocking unauthorized access)
- Rate limiting (preventing abuse)
- CORS handling (allowing cross-origin requests)
Creating a Simple Middleware
Let’s start with a basic logging middleware that prints every request to the console.
Example: Logging Middleware
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Incoming request:", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the Home Page!")
}
func main() {
r := mux.NewRouter()
r.Use(loggingMiddleware)
r.HandleFunc("/", homeHandler)
fmt.Println("Server running on http://localhost:8080")
http.ListenAndServe(":8080", r)
}
Now, every request will be logged.
Adding Authentication Middleware
Want to block unauthorized users? Let’s create an authentication middleware.
Example: Simple Auth Middleware
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if token != "super-secret-token" {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
Now, only requests with the correct token can access protected routes.
Chaining Multiple Middleware Functions
Want logging and authentication? No problem!
Example: Multiple Middleware
r.Use(loggingMiddleware, authMiddleware)
Now, every request is logged and checked for authentication before reaching the handler.
Middleware is a powerful way to enhance your Go web applications. Whether you need security, logging, or custom processing, middleware has your back. Now go make your server smarter!
0 Comments