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

How to Efficiently Handle CORS Preflight Requests in Go?

Susan Sarandon
Release: 2024-12-19 01:02:12
Original
486 people have browsed it

How to Efficiently Handle CORS Preflight Requests in Go?

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

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

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

Usage:

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

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!

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