Home >Backend Development >Golang >How to Elegantly Handle Preflight CORS Requests in Go?
Handling Preflight CORS Requests in Go
When serving cross-site HTTP requests from a Go server, the user agent may send preflight OPTIONS requests to verify the request's safety. This article explores the best practices for handling and responding to these preflight requests elegantly.
Traditionally, using the net/http package, one can check the request method in the handler function:
func AddResourceHandler(rw http.ResponseWriter, r *http.Request) { switch r.Method { case "OPTIONS": // handle preflight case "PUT": // respond to actual request } }
Alternatively, with Gorilla's mux package, one can register a separate preflight handler for each URL path:
r := mux.NewRouter() r.HandleFunc("/someresource/item", AddResourceHandler).Methods("PUT") r.HandleFunc("/someresource/item", PreflightAddResourceHandler).Methods("OPTIONS")
To simplify this process, consider wrapping your REST handler with a CORS handler that handles preflight requests. For example, using net/http's Handle method:
func corsHandler(h http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if (r.Method == "OPTIONS") { //handle preflight in here } else { h.ServeHTTP(w,r) } } }
This wrapper can be used as follows:
http.Handle("/endpoint/", corsHandler(restHandler))
By wrapping the REST handler, you can separate your logic and reuse the CORS handler for all relevant requests, providing a more elegant and maintainable solution.
The above is the detailed content of How to Elegantly Handle Preflight CORS Requests in Go?. For more information, please follow other related articles on the PHP Chinese website!