如何在Go服务器上处理预检CORS请求 [英] How to handle preflight CORS requests on a Go server

查看:1307
本文介绍了如何在Go服务器上处理预检CORS请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在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 包,我可以检查处理程序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
  }
}


b $ b

我还可以使用 Gorilla的 mux 包,并为每个相关网址路径注册预检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请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆