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

How to Efficiently Handle Preflight CORS Requests in Go?

Barbara Streisand
Release: 2024-12-25 01:48:17
Original
309 people have browsed it

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
  }
}
Copy after login

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")
Copy after login

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)
    }
  }
}
Copy after login

You can then wrap the handler like this:

http.Handle("/endpoint/", corsHandler(restHandler))
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template