Handle CORS in Go

Manually add CORS headers like Access-Control-Allow-Origin to Go HTTP responses using a middleware wrapper.

Go does not have a built-in CORS middleware; you must manually add the required headers to your HTTP responses. Use the net/http package to set Access-Control-Allow-Origin and other headers in your handler or a wrapper function.

func corsMiddleware(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, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusNoContent)
			return
		}
		next.ServeHTTP(w, r)
	})
}

func main() {
	http.Handle("/", corsMiddleware(http.HandlerFunc(handler)))
	http.ListenAndServe(":8080", nil)
}

Replace * with your specific domain in production.