How to Implement CORS Middleware in Go

Web
Implement CORS in Go by creating a middleware handler that sets Access-Control headers and handles preflight OPTIONS requests.

Go has no built-in CORS middleware; you must implement it manually or use a third-party library. The standard approach is to write a middleware function that sets the necessary headers on the ResponseWriter before calling the next handler.

func withCORS(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusNoContent)
			return
		}
		next.ServeHTTP(w, r)
	})
}

// Usage: http.ListenAndServe(":8080", withCORS(yourHandler))

This middleware handles preflight OPTIONS requests and sets the required headers for cross-origin requests.