MCPcopy
hub / github.com/gorilla/mux / ExampleCORSMethodMiddleware

Function ExampleCORSMethodMiddleware

example_cors_method_middleware_test.go:11–37  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

9)
10
11func ExampleCORSMethodMiddleware() {
12 r := mux.NewRouter()
13
14 r.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
15 // Handle the request
16 }).Methods(http.MethodGet, http.MethodPut, http.MethodPatch)
17 r.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
18 w.Header().Set("Access-Control-Allow-Origin", "http://example.com")
19 w.Header().Set("Access-Control-Max-Age", "86400")
20 }).Methods(http.MethodOptions)
21
22 r.Use(mux.CORSMethodMiddleware(r))
23
24 rw := httptest.NewRecorder()
25 req, _ := http.NewRequest("OPTIONS", "/foo", nil) // needs to be OPTIONS
26 req.Header.Set("Access-Control-Request-Method", "POST") // needs to be non-empty
27 req.Header.Set("Access-Control-Request-Headers", "Authorization") // needs to be non-empty
28 req.Header.Set("Origin", "http://example.com") // needs to be non-empty
29
30 r.ServeHTTP(rw, req)
31
32 fmt.Println(rw.Header().Get("Access-Control-Allow-Methods"))
33 fmt.Println(rw.Header().Get("Access-Control-Allow-Origin"))
34 // Output:
35 // GET,PUT,PATCH,OPTIONS
36 // http://example.com
37}

Callers

nothing calls this directly

Calls 8

HandleFuncMethod · 0.95
UseMethod · 0.95
ServeHTTPMethod · 0.95
NewRouterFunction · 0.92
CORSMethodMiddlewareFunction · 0.92
GetMethod · 0.80
MethodsMethod · 0.45
HeaderMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…