github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/mux/example_cors_method_middleware_test.go (about)

     1  package mux_test
     2  
     3  import (
     4  	"fmt"
     5  
     6  	http "github.com/hxx258456/ccgo/gmhttp"
     7  	"github.com/hxx258456/ccgo/gmhttp/httptest"
     8  	"github.com/hxx258456/ccgo/mux"
     9  )
    10  
    11  func 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  }