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

How to Elegantly Handle Preflight CORS Requests in Go?

Patricia Arquette
Release: 2025-01-03 08:51:40
Original
152 people have browsed it

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

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

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

This wrapper can be used as follows:

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

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!

source:php.cn
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