...
Source file
src/github.com/gorilla/mux/example_cors_method_middleware_test.go
1 package mux_test
2
3 import (
4 "fmt"
5 "net/http"
6 "net/http/httptest"
7
8 "github.com/gorilla/mux"
9 )
10
11 func ExampleCORSMethodMiddleware() {
12 r := mux.NewRouter()
13
14 r.HandleFunc("/foo", func(w http.ResponseWriter, r *http.Request) {
15
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)
26 req.Header.Set("Access-Control-Request-Method", "POST")
27 req.Header.Set("Access-Control-Request-Headers", "Authorization")
28 req.Header.Set("Origin", "http://example.com")
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
35
36
37 }
38
View as plain text