问题描述
所以我在 Go 中编写了这个 RESTful 后端,它将通过跨站点 HTTP 请求调用,即来自另一个站点提供的内容(实际上,只是另一个端口,但同源策略生效,所以在这里我们是).
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 the same-origin policy kicks in, so here we are).
在这种情况下,在某些情况下,用户代理会发送预检 OPTIONS 请求以检查实际请求是否可以安全发送.
In this scenario, the user agent will, in some cases, send preflight OPTIONS requests to check if the actual request is safe to send.
我的问题是如何在 Go 上下文中最好地处理和充分响应这些预检请求.我构思的方式感觉不是很优雅,我想知道是否还有其他我没有想到的方法.
My question is how to best deal with, and adequately respond to, these preflight requests in a Go context. The ways I have conceived don't feel very elegant, and I'm wondering if there's some other approach to this that I haven't thought of.
使用标准的net/http
包,我可以检查handler func中的请求方法,大概是这样的:
Using the standard net/http
package, I can check the request method in the handler func, perhaps like this:
func AddResourceHandler(rw http.ResponseWriter, r *http.Request) {
switch r.Method {
case "OPTIONS":
// handle preflight
case "PUT":
// respond to actual request
}
}
我也可以使用Gorilla的 mux
包,注册一个每个相关 URL 路径的预检OPTIONS"处理程序.
I can also use Gorilla's mux
package, and register a preflight "OPTIONS" handler for each relevant URL path.
r := mux.NewRouter()
r.HandleFunc("/someresource/item", AddResourceHandler).Methods("PUT")
r.HandleFunc("/someresource/item", PreflightAddResourceHandler).Methods("OPTIONS")
也许对这个问题的回答很简单:是的,这些是你的基本选择.但我认为可能有一些我不知道的最佳实践.
Maybe the response to this question is simply: Yup, those are your basic options. But I thought there might be some best practice around this that I'm unaware of.
推荐答案
分离逻辑并重用您定义的 CORS 处理程序的一种简单方法是包装您的 REST 处理程序.例如,如果你使用 net/http 和 Handle
方法,你总是可以这样做:
One simple way to separate out your logic and re-use the CORS handler you define would be to wrap your REST handler. For example, if you're using net/http and the Handle
method you could always do something like:
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)
}
}
}
你可以这样包装:
http.Handle("/endpoint/", corsHandler(restHandler))
这篇关于如何在 Go 服务器上处理预检 CORS 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!