How to handle preflight CORS requests on a Go server

前端 未结 5 900
时光说笑
时光说笑 2020-12-09 01:48

So I\'m writing this RESTful backend in Go, which will be called with cross-site HTTP requests, i.e. from content served by another site (actually, just another port, but th

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-09 02:03

    gorilla/handlers also has a nice CORS handler: cors.go

    Example usage:

    import (
        "net/http"
    
        "github.com/gorilla/handlers"
        "github.com/gorilla/mux"
    )
    
    func main() {
        r := mux.NewRouter()
        r.HandleFunc("/users", UserEndpoint)
        r.HandleFunc("/projects", ProjectEndpoint)
    
        // Apply the CORS middleware to our top-level router, with the defaults.
        http.ListenAndServe(":8000", handlers.CORS()(r))
    }
    

提交回复
热议问题