How to handle preflight CORS requests on a Go server

前端 未结 5 898
时光说笑
时光说笑 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:06

    I personally find it tedious to add preflight routes for every path that will get an OPTIONS request, so instead I simply add my handler to any OPTIONS method that the request multiplexer (Gorilla in this case) handles as follows:

    router.Methods("OPTIONS").HandlerFunc(
        func(w http.ResponseWriter, r *http.Request){
        myHttpLib.OptionsForBrowserPreflight(w, r)
    })
    

    Note though, that this should come before mapping other routes because if, for example, you have a path like "/foo" and you register that first without specifying any methods for that route, then an OPTIONS request to "/foo" would run instead of your pre-flight code because its the first match.

    This way you can: (1) have just one routing registration for all pre-flights, and (2) have one handler to reuse code and apply logic/rules in a single place for OPTIONS requests.

提交回复
热议问题