http_server_validate.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package fairwind
  2. import (
  3. "regexp"
  4. )
  5. type Validator interface {
  6. Validate(value any) bool
  7. }
  8. type MinLenghtValidator struct {
  9. length int
  10. }
  11. func NewMinLenghtValidator(length int) *MinLenghtValidator {
  12. return &MinLenghtValidator{
  13. length: length,
  14. }
  15. }
  16. func (this *MinLenghtValidator) Validate(value any) bool {
  17. v, ok := value.(string)
  18. if !ok {
  19. return false
  20. }
  21. return len(v) >= this.length
  22. }
  23. type MaxLenghtValidator struct {
  24. length int
  25. }
  26. func NewMaxLenghtValidator(length int) *MaxLenghtValidator {
  27. return &MaxLenghtValidator{
  28. length: length,
  29. }
  30. }
  31. func (this *MaxLenghtValidator) Validate(value any) bool {
  32. v, ok := value.(string)
  33. if !ok {
  34. return false
  35. }
  36. return len(v) <= this.length
  37. }
  38. type ExactLenghtValidator struct {
  39. length int
  40. }
  41. func NewExactLenghtValidator(length int) *ExactLenghtValidator {
  42. return &ExactLenghtValidator{
  43. length: length,
  44. }
  45. }
  46. func (this *ExactLenghtValidator) Validate(value any) bool {
  47. v, ok := value.(string)
  48. if !ok {
  49. return false
  50. }
  51. return len(v) == this.length
  52. }
  53. type RegexValidator struct {
  54. expression *regexp.Regexp
  55. }
  56. func NewRegexValidator(regex string) *RegexValidator {
  57. expression, err := regexp.Compile(regex)
  58. if err != nil {
  59. return &RegexValidator{}
  60. }
  61. return &RegexValidator{
  62. expression: expression,
  63. }
  64. }
  65. func (this *RegexValidator) Validate(value any) bool {
  66. if this.expression == nil {
  67. return false
  68. }
  69. v, ok := value.(string)
  70. if !ok {
  71. return false
  72. }
  73. return this.expression.Match([]byte(v))
  74. }