Prev Next

Golang / GoLang Production Patterns and Web Standards Interview Questions

How do you implement JWT authentication middleware in Go?

JWT (JSON Web Token) authentication middleware validates the token on every request, extracts claims, and attaches them to the request context for use by downstream handlers.

import "github.com/golang-jwt/jwt/v5"

type Claims struct {
    UserID int    `json:"user_id"`
    Role   string `json:"role"`
    jwt.RegisteredClaims
}

type contextKey string
const claimsKey contextKey = "claims"

func jwtMiddleware(secret []byte) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            // Extract token from Authorization: Bearer 
            auth := r.Header.Get("Authorization")
            if !strings.HasPrefix(auth, "Bearer ") {
                writeJSON(w, http.StatusUnauthorized,
                    map[string]string{"error": "missing bearer token"})
                return
            }
            tokenString := strings.TrimPrefix(auth, "Bearer ")

            // Parse and validate
            var claims Claims
            token, err := jwt.ParseWithClaims(tokenString, &claims,
                func(token *jwt.Token) (any, error) {
                    if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
                        return nil, fmt.Errorf("unexpected signing method: %v",
                            token.Header["alg"])
                    }
                    return secret, nil
                })

            if err != nil || !token.Valid {
                writeJSON(w, http.StatusUnauthorized,
                    map[string]string{"error": "invalid or expired token"})
                return
            }

            // Attach claims to context
            ctx := context.WithValue(r.Context(), claimsKey, &claims)
            next.ServeHTTP(w, r.WithContext(ctx))
        })
    }
}

// Helper to extract claims in handlers
func claimsFromCtx(ctx context.Context) (*Claims, bool) {
    c, ok := ctx.Value(claimsKey).(*Claims)
    return c, ok
}
Why should JWT middleware validate the 'alg' (algorithm) claim before verifying the token?
After JWT middleware validates the token, how does it pass the claims to subsequent handlers?

Invest now in Acorns!!! 🚀 Join Acorns and get your $5 bonus!

Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!

Earn passively and while sleeping

Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.

Invest now!!! Get Free equity stock (US, UK only)!

Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.

The Robinhood app makes it easy to trade stocks, crypto and more.


Webull! Receive free stock by signing up using the link: Webull signup.

More Related questions...

Why does Go treat errors as values instead of using exceptions, and what are the advantages? How do you wrap errors in Go 1.13+ and use errors.Is and errors.As for inspection? What are the best practices for defining custom error types in Go? What is context.Context in Go, what does it carry, and how do you create one? How does context propagate through an HTTP request lifecycle in Go? What are the best practices and anti-patterns for using context.WithValue? How do you build a production-ready HTTP server using Go's standard net/http package? What is the standard Go HTTP middleware signature and how do you chain multiple middleware? How has http.ServeMux evolved in Go 1.22 and what routing patterns does it support? How do you encode and decode JSON in Go and what are the common pitfalls? What are the rules for writing HTTP responses correctly in Go handlers? How do you implement dependency injection in Go without a framework? How do you implement structured logging in Go using the slog package? What are the idiomatic Go patterns for managing application configuration? How do you interact with a SQL database in Go using the standard database/sql package? How do you implement graceful shutdown of an HTTP server in Go? How do you test HTTP handlers in Go without starting a real server? What are table-driven tests in Go and why are they the preferred testing pattern? How do you write testable Go code using interfaces and mocks without a framework? How do you implement rate limiting in a Go HTTP server? How do you implement CORS correctly in a Go HTTP server? How and when should you use panic and recover in production Go code? How do you manage environment-specific settings and feature flags in Go? How do you implement health check and readiness endpoints for a Go service? How do you add observability (metrics and distributed tracing) to a Go service? How do build tags work in Go and when do you use them? What are the best practices for using Go's HTTP client in production? What patterns make HTTP error handling consistent and DRY in Go? What are the common API versioning strategies in Go HTTP services? How do Go programs handle OS signals and interact with the operating system? How do you profile a Go service in production using pprof? How does Go's module system work and what are the key commands? How do you validate HTTP request inputs in Go without a framework? How do you implement streaming HTTP responses in Go? How do you write and interpret Go benchmarks? How do you embed static files into a Go binary using go:embed? How do you implement timeouts for non-HTTP operations like database queries and external calls? What are the conventions for returning structured error responses from a Go REST API? How do you implement pagination for list endpoints in a Go REST API? How do you implement JWT authentication middleware in Go? How do you implement HTTP response caching in a Go service? How does gRPC work in Go and when would you choose it over REST/JSON? What linters and static analysis tools are essential for production Go code quality? What is the recommended project structure for a production Go service? How do you implement load shedding and request queue limits in a Go HTTP server? How do you correctly propagate errors from concurrent goroutines in a Go service? How do you document a Go REST API and maintain an OpenAPI specification? What is the production readiness checklist for a Go HTTP service?
Show more question and Answers...

GoLang System Architecture and Testing Interview Questions

Comments & Discussions