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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
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...
