How to Implement Authentication Middleware in Go

Web
Implement Go authentication middleware by wrapping handlers to validate request headers and reject unauthorized access with a 401 status.

Implement authentication middleware by creating a function that wraps your handler, checks for credentials in the request headers, and returns a 401 status if they are missing or invalid.

func AuthMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        token := r.Header.Get("Authorization")
        if token == "" || !isValidToken(token) {
            http.Error(w, "Unauthorized", http.StatusUnauthorized)
            return
        }
        next.ServeHTTP(w, r)
    })
}

func isValidToken(token string) bool {
    return token == "secret-token" // Replace with real validation logic
}

Apply it to your router using http.HandlerFunc or a framework like gorilla/mux.