如何使用gorilla处理程序从移动设备中允许OPTIONS方法?

时间:2016-07-14 13:57:19

标签: go gorilla

需要接受来自移动设备的OPTIONS方法, 尝试了多种方法,并采取了奇怪的行为:

尝试这个时,我从客户端获得403: (客户端在OPTIONS之前发送POST

  import (
    "net/http"

    "github.com/gorilla/handlers"
    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/users", UserEndpoint)
    r.HandleFunc("/projects", ProjectEndpoint)

    methods := handlers.AllowedMethods([]string{"OPTIONS", "DELETE", "GET", "HEAD", "POST"}

    http.ListenAndServe(":8000", handlers.CORS(methods)(r))
}

如果我省略methods

        http.ListenAndServe(":8000", handlers.CORS()(r))

我得到403未经授权

同时使用它,删除了GET方法:

methods := handlers.AllowedMethods([]string{"OPTIONS"}

http.ListenAndServe(":8000", handlers.CORS(methods)(r))

但仍然可以 从浏览器中的rest客户端尝试获得200 GET(chromes DHC)

但如果删除OPTIONS

methods := handlers.AllowedMethods([]string{"DELETE", "GET", "HEAD", "POST"}

http.ListenAndServe(":8000", handlers.CORS(methods)(r))

我得到405

第一个示例基于大猩猩处理程序docs

关于这个问题的任何想法?

由于

2 个答案:

答案 0 :(得分:3)

你真的需要了解正在发出的请求,但我遇到了类似的问题并通过以下方式解决了这个问题:

handlers.CORS(
        handlers.AllowedOrigins([]string{"*"}),
        handlers.AllowedMethods([]string{"POST"}),
        handlers.AllowedHeaders([]string{"Content-Type", "X-Requested-With"}),
    )(router)

我需要制作的请求(模仿预检)是:

curl -H "Origin: http://example.com" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: X-Requested-With" \
-X OPTIONS --verbose http://127.0.0.1:8080/products

真正的AllowedHeaders功能完全不同。我添加后,403错误就消失了。

答案 1 :(得分:0)

如果你看cors.go选项是专门处理的:

corsOptionMethod           string = "OPTIONS"
...

    if r.Method == corsOptionMethod {
        if ch.ignoreOptions {
            ch.h.ServeHTTP(w, r)
            return
        }

        if _, ok := r.Header[corsRequestMethodHeader]; !ok {
            w.WriteHeader(http.StatusBadRequest)
            return
        }

        method := r.Header.Get(corsRequestMethodHeader)
        if !ch.isMatch(method, ch.allowedMethods) {
            w.WriteHeader(http.StatusMethodNotAllowed)
            return
        }
...

所以405是http.StatusMethodNotAllowed,所以也许它不是CORs请求头?

还有一种用于独立处理选项的IngoreOptions方法:http://www.gorillatoolkit.org/pkg/handlers#IgnoreOptions - 也许这适用于您的情况,您可以忽略它,或者自己处理选项。