validator.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2021 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package validator // import "miniflux.app/validator"
  5. import (
  6. "errors"
  7. "fmt"
  8. "net/url"
  9. "miniflux.app/locale"
  10. )
  11. // ValidationError represents a validation error.
  12. type ValidationError struct {
  13. TranslationKey string
  14. }
  15. // NewValidationError initializes a validation error.
  16. func NewValidationError(translationKey string) *ValidationError {
  17. return &ValidationError{TranslationKey: translationKey}
  18. }
  19. func (v *ValidationError) String() string {
  20. return locale.NewPrinter("en_US").Printf(v.TranslationKey)
  21. }
  22. func (v *ValidationError) Error() error {
  23. return errors.New(v.String())
  24. }
  25. // ValidateRange makes sure the offset/limit values are valid.
  26. func ValidateRange(offset, limit int) error {
  27. if offset < 0 {
  28. return fmt.Errorf(`Offset value should be >= 0`)
  29. }
  30. if limit < 0 {
  31. return fmt.Errorf(`Limit value should be >= 0`)
  32. }
  33. return nil
  34. }
  35. // ValidateDirection makes sure the sorting direction is valid.
  36. func ValidateDirection(direction string) error {
  37. switch direction {
  38. case "asc", "desc":
  39. return nil
  40. }
  41. return fmt.Errorf(`Invalid direction, valid direction values are: "asc" or "desc"`)
  42. }
  43. func isValidURL(absoluteURL string) bool {
  44. _, err := url.ParseRequestURI(absoluteURL)
  45. return err == nil
  46. }