Home >Backend Development >Golang >How to Efficiently Handle Preflight CORS Requests in Go?

How to Efficiently Handle Preflight CORS Requests in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-25 01:48:17312browse

How to Efficiently Handle Preflight CORS Requests in Go?

Handling Preflight CORS Requests in Go

In developing cross-site HTTP requests, you may encounter preflight OPTIONS requests to check the request's safety. Addressing these requests appropriately is crucial in a Go context.

One basic approach is to 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
  }
}

Another option is utilizing Gorilla's mux package, registering a preflight "OPTIONS" handler for relevant URL paths:

r := mux.NewRouter()
r.HandleFunc("/someresource/item", AddResourceHandler).Methods("PUT")
r.HandleFunc("/someresource/item", PreflightAddResourceHandler).Methods("OPTIONS")

However, for a more elegant approach, consider wrapping your REST handler:

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)
    }
  }
}

You can then wrap the handler like this:

http.Handle("/endpoint/", corsHandler(restHandler))

By separating out your logic and re-using the CORS handler, you streamline your code and enhance its maintainability.

The above is the detailed content of How to Efficiently Handle Preflight CORS Requests in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn