header_rules.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package v4
  2. import (
  3. "net/http"
  4. "strings"
  5. )
  6. // validator houses a set of rule needed for validation of a
  7. // string value
  8. type rules []rule
  9. // rule interface allows for more flexible rules and just simply
  10. // checks whether or not a value adheres to that rule
  11. type rule interface {
  12. IsValid(value string) bool
  13. }
  14. // IsValid will iterate through all rules and see if any rules
  15. // apply to the value and supports nested rules
  16. func (r rules) IsValid(value string) bool {
  17. for _, rule := range r {
  18. if rule.IsValid(value) {
  19. return true
  20. }
  21. }
  22. return false
  23. }
  24. // mapRule generic rule for maps
  25. type mapRule map[string]struct{}
  26. // IsValid for the map rule satisfies whether it exists in the map
  27. func (m mapRule) IsValid(value string) bool {
  28. _, ok := m[value]
  29. return ok
  30. }
  31. // whitelist is a generic rule for whitelisting
  32. type whitelist struct {
  33. rule
  34. }
  35. // IsValid for whitelist checks if the value is within the whitelist
  36. func (w whitelist) IsValid(value string) bool {
  37. return w.rule.IsValid(value)
  38. }
  39. // blacklist is a generic rule for blacklisting
  40. type blacklist struct {
  41. rule
  42. }
  43. // IsValid for whitelist checks if the value is within the whitelist
  44. func (b blacklist) IsValid(value string) bool {
  45. return !b.rule.IsValid(value)
  46. }
  47. type patterns []string
  48. // IsValid for patterns checks each pattern and returns if a match has
  49. // been found
  50. func (p patterns) IsValid(value string) bool {
  51. for _, pattern := range p {
  52. if strings.HasPrefix(http.CanonicalHeaderKey(value), pattern) {
  53. return true
  54. }
  55. }
  56. return false
  57. }
  58. // inclusiveRules rules allow for rules to depend on one another
  59. type inclusiveRules []rule
  60. // IsValid will return true if all rules are true
  61. func (r inclusiveRules) IsValid(value string) bool {
  62. for _, rule := range r {
  63. if !rule.IsValid(value) {
  64. return false
  65. }
  66. }
  67. return true
  68. }