formats.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2015 go-swagger maintainers
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package validate
  15. import (
  16. "reflect"
  17. "github.com/go-openapi/spec"
  18. "github.com/go-openapi/strfmt"
  19. )
  20. type formatValidator struct {
  21. Format string
  22. Path string
  23. In string
  24. KnownFormats strfmt.Registry
  25. }
  26. func (f *formatValidator) SetPath(path string) {
  27. f.Path = path
  28. }
  29. func (f *formatValidator) Applies(source interface{}, kind reflect.Kind) bool {
  30. doit := func() bool {
  31. if source == nil {
  32. return false
  33. }
  34. switch source := source.(type) {
  35. case *spec.Items:
  36. return kind == reflect.String && f.KnownFormats.ContainsName(source.Format)
  37. case *spec.Parameter:
  38. return kind == reflect.String && f.KnownFormats.ContainsName(source.Format)
  39. case *spec.Schema:
  40. return kind == reflect.String && f.KnownFormats.ContainsName(source.Format)
  41. case *spec.Header:
  42. return kind == reflect.String && f.KnownFormats.ContainsName(source.Format)
  43. }
  44. return false
  45. }
  46. r := doit()
  47. debugLog("format validator for %q applies %t for %T (kind: %v)\n", f.Path, r, source, kind)
  48. return r
  49. }
  50. func (f *formatValidator) Validate(val interface{}) *Result {
  51. result := new(Result)
  52. debugLog("validating \"%v\" against format: %s", val, f.Format)
  53. if err := FormatOf(f.Path, f.In, f.Format, val.(string), f.KnownFormats); err != nil {
  54. result.AddErrors(err)
  55. }
  56. if result.HasErrors() {
  57. return result
  58. }
  59. return nil
  60. }