doubi6669 2014-04-09 19:20
浏览 280
已采纳

如何在Go服务器上处理预检CORS请求

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).

In this scenario, the user agent will, in some cases, send preflight OPTIONS requests to check if the actual request is safe to send.

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.

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
  }
}

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.

  • 写回答

4条回答 默认 最新

  • dongzhuonao8429 2014-04-09 20:54
    关注

    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)
        }
      }
    }
    

    You can wrap like this:

    http.Handle("/endpoint/", corsHandler(restHandler))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献