PageRenderTime 48ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/github.com/storageos/go-api/validation.go

https://bitbucket.org/Jake-Qu/kubernetes-mirror
Go | 74 lines | 48 code | 12 blank | 14 comment | 8 complexity | 262cb55572fea95da60eaea130b047f9 MD5 | raw file
Possible License(s): MIT, MPL-2.0-no-copyleft-exception, 0BSD, CC0-1.0, BSD-2-Clause, Apache-2.0, BSD-3-Clause
  1. package storageos
  2. import (
  3. "errors"
  4. "regexp"
  5. )
  6. const (
  7. // IDFormat are the characters allowed to represent an ID.
  8. IDFormat = `[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`
  9. // NameFormat are the characters allowed to represent a name.
  10. NameFormat = `[a-zA-Z0-9][a-zA-Z0-9~_.-]+`
  11. )
  12. var (
  13. // IDPattern is a regular expression to validate a unique id against the
  14. // collection of restricted characters.
  15. IDPattern = regexp.MustCompile(`^` + IDFormat + `$`)
  16. // NamePattern is a regular expression to validate names against the
  17. // collection of restricted characters.
  18. NamePattern = regexp.MustCompile(`^` + NameFormat + `$`)
  19. ErrNoRef = errors.New("no ref provided or incorrect format")
  20. ErrNoNamespace = errors.New("no namespace provided or incorrect format")
  21. )
  22. // ValidateNamespaceAndRef returns true if both the namespace and ref are valid.
  23. func ValidateNamespaceAndRef(namespace, ref string) error {
  24. if !IsUUID(ref) && !IsName(ref) {
  25. return ErrNoRef
  26. }
  27. if !IsName(namespace) {
  28. return ErrNoNamespace
  29. }
  30. return nil
  31. }
  32. // ValidateNamespace returns true if the namespace uses a valid name.
  33. func ValidateNamespace(namespace string) error {
  34. if !IsName(namespace) {
  35. return ErrNoNamespace
  36. }
  37. return nil
  38. }
  39. // IsUUID returns true if the string input is a valid UUID string.
  40. func IsUUID(s string) bool {
  41. return IDPattern.MatchString(s)
  42. }
  43. // IsName returns true if the string input is a valid Name string.
  44. func IsName(s string) bool {
  45. return NamePattern.MatchString(s)
  46. }
  47. // namespacedPath checks for valid input and returns api path for a namespaced
  48. // objectType. Use namespacedRefPath for objects.
  49. func namespacedPath(namespace, objectType string) (string, error) {
  50. if err := ValidateNamespace(namespace); err != nil {
  51. return "", err
  52. }
  53. return "/namespaces/" + namespace + "/" + objectType, nil
  54. }
  55. // namespacedRefPath checks for valid input and returns api path for a single
  56. // namespaced object. Use namespacedPath for objects type path.
  57. func namespacedRefPath(namespace, objectType, ref string) (string, error) {
  58. if err := ValidateNamespaceAndRef(namespace, ref); err != nil {
  59. return "", err
  60. }
  61. return "/namespaces/" + namespace + "/" + objectType + "/" + ref, nil
  62. }