Golang / GoLang Production Patterns and Web Standards Interview Questions
How do you implement CORS correctly in a Go HTTP server?
Cross-Origin Resource Sharing (CORS) is required when a browser-based frontend on one domain calls an API on a different domain. Go has no built-in CORS support — you implement it as middleware or use a library like rs/cors.
// Manual CORS middleware (for learning â use a library in production) func corsMiddleware(allowedOrigins []string) func(http.Handler) http.Handler { originSet := make(map[string]bool) for _, o := range allowedOrigins { originSet[o] = true } return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { origin := r.Header.Get("Origin") if originSet[origin] { w.Header().Set("Access-Control-Allow-Origin", origin) w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Request-ID") w.Header().Set("Access-Control-Allow-Credentials", "true") w.Header().Set("Access-Control-Max-Age", "86400") // 24h preflight cache } // Handle preflight OPTIONS request if r.Method == http.MethodOptions { w.WriteHeader(http.StatusNoContent) return } next.ServeHTTP(w, r) }) } } // Usage handler := corsMiddleware([]string{ "https://app.example.com", "https://admin.example.com", })(mux) // Production: use github.com/rs/cors // c := cors.New(cors.Options{ // AllowedOrigins: []string{"https://app.example.com"}, // AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"}, // AllowedHeaders: []string{"Authorization", "Content-Type"}, // AllowCredentials: true, // }) // handler = c.Handler(mux)
Security note: never use Access-Control-Allow-Origin: * together with Access-Control-Allow-Credentials: true — browsers reject this combination. Always whitelist specific origins when credentials are involved.
More Related questions...