You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

52 lines
1.7 KiB

  1. package mux_test
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/gorilla/mux"
  6. )
  7. // This example demonstrates setting a regular expression matcher for
  8. // the header value. A plain word will match any value that contains a
  9. // matching substring as if the pattern was wrapped with `.*`.
  10. func ExampleRoute_HeadersRegexp() {
  11. r := mux.NewRouter()
  12. route := r.NewRoute().HeadersRegexp("Accept", "html")
  13. req1, _ := http.NewRequest("GET", "example.com", nil)
  14. req1.Header.Add("Accept", "text/plain")
  15. req1.Header.Add("Accept", "text/html")
  16. req2, _ := http.NewRequest("GET", "example.com", nil)
  17. req2.Header.Set("Accept", "application/xhtml+xml")
  18. matchInfo := &mux.RouteMatch{}
  19. fmt.Printf("Match: %v %q\n", route.Match(req1, matchInfo), req1.Header["Accept"])
  20. fmt.Printf("Match: %v %q\n", route.Match(req2, matchInfo), req2.Header["Accept"])
  21. // Output:
  22. // Match: true ["text/plain" "text/html"]
  23. // Match: true ["application/xhtml+xml"]
  24. }
  25. // This example demonstrates setting a strict regular expression matcher
  26. // for the header value. Using the start and end of string anchors, the
  27. // value must be an exact match.
  28. func ExampleRoute_HeadersRegexp_exactMatch() {
  29. r := mux.NewRouter()
  30. route := r.NewRoute().HeadersRegexp("Origin", "^https://example.co$")
  31. yes, _ := http.NewRequest("GET", "example.co", nil)
  32. yes.Header.Set("Origin", "https://example.co")
  33. no, _ := http.NewRequest("GET", "example.co.uk", nil)
  34. no.Header.Set("Origin", "https://example.co.uk")
  35. matchInfo := &mux.RouteMatch{}
  36. fmt.Printf("Match: %v %q\n", route.Match(yes, matchInfo), yes.Header["Origin"])
  37. fmt.Printf("Match: %v %q\n", route.Match(no, matchInfo), no.Header["Origin"])
  38. // Output:
  39. // Match: true ["https://example.co"]
  40. // Match: false ["https://example.co.uk"]
  41. }