-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathexample_route_test.go
69 lines (54 loc) · 2.43 KB
/
example_route_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package mux_test
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
// This example demonstrates setting a regular expression matcher for
// the header value. A plain word will match any value that contains a
// matching substring as if the pattern was wrapped with `.*`.
func ExampleRoute_HeadersRegexp() {
r := mux.NewRouter()
route := r.NewRoute().HeadersRegexp("Accept", "html")
req1, _ := http.NewRequest("GET", "example.com", nil)
req1.Header.Add("Accept", "text/plain")
req1.Header.Add("Accept", "text/html")
req2, _ := http.NewRequest("GET", "example.com", nil)
req2.Header.Set("Accept", "application/xhtml+xml")
matchInfo := &mux.RouteMatch{}
fmt.Printf("Match: %v %q\n", route.Match(req1, matchInfo), req1.Header["Accept"])
fmt.Printf("Match: %v %q\n", route.Match(req2, matchInfo), req2.Header["Accept"])
// Output:
// Match: true ["text/plain" "text/html"]
// Match: true ["application/xhtml+xml"]
}
// This example demonstrates setting a strict regular expression matcher
// for the header value. Using the start and end of string anchors, the
// value must be an exact match.
func ExampleRoute_HeadersRegexp_exactMatch() {
r := mux.NewRouter()
route := r.NewRoute().HeadersRegexp("Origin", "^https://example.co$")
yes, _ := http.NewRequest("GET", "example.co", nil)
yes.Header.Set("Origin", "https://example.co")
no, _ := http.NewRequest("GET", "example.co.uk", nil)
no.Header.Set("Origin", "https://example.co.uk")
matchInfo := &mux.RouteMatch{}
fmt.Printf("Match: %v %q\n", route.Match(yes, matchInfo), yes.Header["Origin"])
fmt.Printf("Match: %v %q\n", route.Match(no, matchInfo), no.Header["Origin"])
// Output:
// Match: true ["https://example.co"]
// Match: false ["https://example.co.uk"]
}
// This example demonstrates alias pattern registration and usage on router
func ExampleRoute_RegisterPattern() {
r := mux.NewRouter().RegisterPattern("uuid", "[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}")
route := r.Path("/category/{id:uuid}")
yes, _ := http.NewRequest("GET", "example.co/category/abe193ed-e0bc-4e1b-8e3c-736d5b381b60", nil)
no, _ := http.NewRequest("GET", "example.co/category/42", nil)
mathInfo := &mux.RouteMatch{}
fmt.Printf("Match: %v %q\n", route.Match(yes, mathInfo), yes.URL.Path)
fmt.Printf("Match: %v %q\n", route.Match(no, mathInfo), no.URL.Path)
// Output
// Match: true /category/abe193ed-e0bc-4e1b-8e3c-736d5b381b60
// Match: false /category/42
}