[Go] httprouter 自动 OPTIONS 响应 和 CORS

httprouter 是 Gin framework 使用的路由组件。

要对 OPTIONS 请求自动响应,比如支持 CORS 请求或者设置请求头,可用 Router.GlobalOPTIONS。

router.GlobalOPTIONS = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    if r.Header.Get("Access-Control-Request-Method") != "" {
        // Set CORS headers
        header := w.Header()
        header.Set("Access-Control-Allow-Methods", r.Header.Get("Allow"))
        header.Set("Access-Control-Allow-Origin", "*")
    }

    // Adjust status code to 204
    w.WriteHeader(http.StatusNoContent)
})

[Go] CORS 支持多个 origin 访问的思路 (Access-Control-Allow-Origin 部分)

Refer:Golang httprouter注意事项

Refer:https://github.com/julienschmidt/httprouter#automatic-options-responses-and-cors

Link:https://www.cnblogs.com/farwish/p/12917072.html