CORS Middleware

suggest change
func CORS(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        origin := r.Header.Get("Origin")
        w.Header().Set("Access-Control-Allow-Origin", origin)
        if r.Method == "OPTIONS" {
            w.Header().Set("Access-Control-Allow-Credentials", "true")
            w.Header().Set("Access-Control-Allow-Methods", "GET,POST")

            w.Header().Set("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, Authorization")
            return
        } else {
            h.ServeHTTP(w, r)
        }
    })
}

func main() {
    http.HandleFunc("/login", Logger(CORS(loginHandler)))
    http.ListenAndServe(":8080", nil)
}

Echoing the request Origin as Access-Control-Allow-Origin allows that site to read the response. Do not combine that with Access-Control-Allow-Credentials unless the origin is an allowlist you control. The credential header above is set only for OPTIONS, not for the request that follows.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents