github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/mux/example_route_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/mux" 8 ) 9 10 // This example demonstrates setting a regular expression matcher for 11 // the header value. A plain word will match any value that contains a 12 // matching substring as if the pattern was wrapped with `.*`. 13 func ExampleRoute_HeadersRegexp() { 14 r := mux.NewRouter() 15 route := r.NewRoute().HeadersRegexp("Accept", "html") 16 17 req1, _ := http.NewRequest("GET", "example.com", nil) 18 req1.Header.Add("Accept", "text/plain") 19 req1.Header.Add("Accept", "text/html") 20 21 req2, _ := http.NewRequest("GET", "example.com", nil) 22 req2.Header.Set("Accept", "application/xhtml+xml") 23 24 matchInfo := &mux.RouteMatch{} 25 fmt.Printf("Match: %v %q\n", route.Match(req1, matchInfo), req1.Header["Accept"]) 26 fmt.Printf("Match: %v %q\n", route.Match(req2, matchInfo), req2.Header["Accept"]) 27 // Output: 28 // Match: true ["text/plain" "text/html"] 29 // Match: true ["application/xhtml+xml"] 30 } 31 32 // This example demonstrates setting a strict regular expression matcher 33 // for the header value. Using the start and end of string anchors, the 34 // value must be an exact match. 35 func ExampleRoute_HeadersRegexp_exactMatch() { 36 r := mux.NewRouter() 37 route := r.NewRoute().HeadersRegexp("Origin", "^https://example.co$") 38 39 yes, _ := http.NewRequest("GET", "example.co", nil) 40 yes.Header.Set("Origin", "https://example.co") 41 42 no, _ := http.NewRequest("GET", "example.co.uk", nil) 43 no.Header.Set("Origin", "https://example.co.uk") 44 45 matchInfo := &mux.RouteMatch{} 46 fmt.Printf("Match: %v %q\n", route.Match(yes, matchInfo), yes.Header["Origin"]) 47 fmt.Printf("Match: %v %q\n", route.Match(no, matchInfo), no.Header["Origin"]) 48 // Output: 49 // Match: true ["https://example.co"] 50 // Match: false ["https://example.co.uk"] 51 }