How to Handle CORS Properly in Go

Web
Manually set Access-Control-Allow-Origin headers in Go HTTP handlers to enable cross-origin requests.

Go does not have a built-in CORS middleware; you must manually set the Access-Control-Allow-Origin and related headers in your HTTP handlers. For a simple server allowing all origins, add the following headers to every response, including OPTIONS preflight requests.

package main

import (
	"net/http"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/api", 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 == http.MethodOptions {
			http.Error(w, "", http.StatusNoContent)
			return
		}
		w.Write([]byte("Hello"))
	})
	http.ListenAndServe(":8080", mux)
}