Handling CORS Preflight Requests with Go
In a RESTful backend server written in Go, handling cross-origin HTTP requests requires addressing preflight CORS requests. Here's how to effectively deal with them:
1. Manual Method Check:
In net/http, the request method can be checked in the handler function. For instance:
func AddResourceHandler(rw http.ResponseWriter, r *http.Request) { switch r.Method { case "OPTIONS": // Preflight handling logic case "PUT": // Actual request response } }
2. Gorilla Mux Package:
Gorilla Mux allows registering a separate preflight handler for each URL path. For example:
r := mux.NewRouter() r.HandleFunc("/someresource/item", AddResourceHandler).Methods("PUT") r.HandleFunc("/someresource/item", PreflightAddResourceHandler).Methods("OPTIONS")
3. HTTP Handler Wrapper:
To decouple logic and reuse the CORS handler, consider wrapping the REST handler. For example, in net/http:
func corsHandler(h http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Method == "OPTIONS" { // Preflight handling } else { h.ServeHTTP(w, r) } } }
Usage:
http.Handle("/endpoint/", corsHandler(restHandler))
These approaches provide elegant solutions for handling CORS preflight requests in Go. Choose the one that aligns best with your application architecture.
The above is the detailed content of How to Efficiently Handle CORS Preflight Requests in Go?. For more information, please follow other related articles on the PHP Chinese website!