本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.0KB

  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.(type) {
  35. case *spec.Items:
  36. it := source.(*spec.Items)
  37. return kind == reflect.String && f.KnownFormats.ContainsName(it.Format)
  38. case *spec.Parameter:
  39. par := source.(*spec.Parameter)
  40. return kind == reflect.String && f.KnownFormats.ContainsName(par.Format)
  41. case *spec.Schema:
  42. sch := source.(*spec.Schema)
  43. return kind == reflect.String && f.KnownFormats.ContainsName(sch.Format)
  44. case *spec.Header:
  45. hdr := source.(*spec.Header)
  46. return kind == reflect.String && f.KnownFormats.ContainsName(hdr.Format)
  47. }
  48. return false
  49. }
  50. r := doit()
  51. debugLog("format validator for %q applies %t for %T (kind: %v)\n", f.Path, r, source, kind)
  52. return r
  53. }
  54. func (f *formatValidator) Validate(val interface{}) *Result {
  55. result := new(Result)
  56. debugLog("validating \"%v\" against format: %s", val, f.Format)
  57. if err := FormatOf(f.Path, f.In, f.Format, val.(string), f.KnownFormats); err != nil {
  58. result.AddErrors(err)
  59. }
  60. if result.HasErrors() {
  61. return result
  62. }
  63. return nil
  64. }
上海开阖软件有限公司 沪ICP备12045867号-1