1 Star 0 Fork 0

missyoyo/mux

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
example_cors_method_middleware_test.go 1.15 KB
一键复制 编辑 原始数据 按行查看 历史
package mux_test
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/gorilla/mux"
)
func ExampleCORSMethodMiddleware() {
r := mux.NewRouter()
r.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
// Handle the request
}).Methods(http.MethodGet, http.MethodPut, http.MethodPatch)
r.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "http://example.com")
w.Header().Set("Access-Control-Max-Age", "86400")
}).Methods(http.MethodOptions)
r.Use(mux.CORSMethodMiddleware(r))
rw := httptest.NewRecorder()
req, _ := http.NewRequest("OPTIONS", "/foo", nil) // needs to be OPTIONS
req.Header.Set("Access-Control-Request-Method", "POST") // needs to be non-empty
req.Header.Set("Access-Control-Request-Headers", "Authorization") // needs to be non-empty
req.Header.Set("Origin", "http://example.com") // needs to be non-empty
r.ServeHTTP(rw, req)
fmt.Println(rw.Header().Get("Access-Control-Allow-Methods"))
fmt.Println(rw.Header().Get("Access-Control-Allow-Origin"))
// Output:
// GET,PUT,PATCH,OPTIONS
// http://example.com
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/missyoyo/mux.git
git@gitee.com:missyoyo/mux.git
missyoyo
mux
mux
master

搜索帮助