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.
 
 
 

51 lines
969 B

  1. package handlers
  2. import (
  3. "net/http"
  4. "strings"
  5. )
  6. // Kind of match to apply to the header check.
  7. type HeaderMatchType int
  8. const (
  9. HmEquals HeaderMatchType = iota
  10. HmStartsWith
  11. HmEndsWith
  12. HmContains
  13. )
  14. // Check if the specified header matches the test string, applying the header match type
  15. // specified.
  16. func HeaderMatch(hdr http.Header, nm string, matchType HeaderMatchType, test string) bool {
  17. // First get the header value
  18. val := hdr[http.CanonicalHeaderKey(nm)]
  19. if len(val) == 0 {
  20. return false
  21. }
  22. // Prepare the match test
  23. test = strings.ToLower(test)
  24. for _, v := range val {
  25. v = strings.Trim(strings.ToLower(v), " \n\t")
  26. switch matchType {
  27. case HmEquals:
  28. if v == test {
  29. return true
  30. }
  31. case HmStartsWith:
  32. if strings.HasPrefix(v, test) {
  33. return true
  34. }
  35. case HmEndsWith:
  36. if strings.HasSuffix(v, test) {
  37. return true
  38. }
  39. case HmContains:
  40. if strings.Contains(v, test) {
  41. return true
  42. }
  43. }
  44. }
  45. return false
  46. }