How to handle preflight CORS requests on a Go server

前端 未结 5 887
时光说笑
时光说笑 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 01:58

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

提交回复
热议问题