http_server_validate.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 RegexValidator struct {
  39. expression *regexp.Regexp
  40. }
  41. func NewRegexValidator(regex string) *RegexValidator {
  42. expression, err := regexp.Compile(regex)
  43. if err != nil {
  44. return &RegexValidator{}
  45. }
  46. return &RegexValidator{
  47. expression: expression,
  48. }
  49. }
  50. func (this *RegexValidator) Validate(value any) bool {
  51. if this.expression == nil {
  52. return false
  53. }
  54. v, ok := value.(string)
  55. if !ok {
  56. return false
  57. }
  58. return this.expression.Match([]byte(v))
  59. }