Improve CORS Method Middleware (#477)
* More sensical CORSMethodMiddleware * Only sets Access-Control-Allow-Methods on valid preflight requests * Does not return after setting the Access-Control-Allow-Methods header * Does not append OPTIONS header to Access-Control-Allow-Methods regardless of whether there is an OPTIONS method matcher * Adds tests for the listed behavior * Add example for CORSMethodMiddleware * Do not check for preflight and add documentation to the README * Use http.MethodOptions instead of "OPTIONS" * Add link to CORSMethodMiddleware section to readme * Add test for unmatching route methods * Rename CORS Method Middleware to Handling CORS Requests in README * Link CORSMethodMiddleware in README to godoc * Break CORSMethodMiddleware doc into bullets for readability * Add comment about specifying OPTIONS to example in README for CORSMethodMiddleware * Document cURL command used for testing CORS Method Middleware * Update comment in example to "Handle the request" * Add explicit comment about OPTIONS matchers to CORSMethodMiddleware doc * Update circleci config to only check gofmt diff on latest go version * Break up gofmt and go vet checks into separate steps. * Use canonical circleci config
This commit is contained in:
committed by
Matt Silverlock
parent
d70f7b4baa
commit
0534769016
37
example_cors_method_middleware_test.go
Normal file
37
example_cors_method_middleware_test.go
Normal file
@@ -0,0 +1,37 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user