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.

headers.go 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 errors
  15. import (
  16. "fmt"
  17. "net/http"
  18. )
  19. // Validation represents a failure of a precondition
  20. type Validation struct {
  21. code int32
  22. Name string
  23. In string
  24. Value interface{}
  25. message string
  26. Values []interface{}
  27. }
  28. func (e *Validation) Error() string {
  29. return e.message
  30. }
  31. // Code the error code
  32. func (e *Validation) Code() int32 {
  33. return e.code
  34. }
  35. // ValidateName produces an error message name for an aliased property
  36. func (e *Validation) ValidateName(name string) *Validation {
  37. if e.Name == "" && name != "" {
  38. e.Name = name
  39. e.message = name + e.message
  40. }
  41. return e
  42. }
  43. const (
  44. contentTypeFail = `unsupported media type %q, only %v are allowed`
  45. responseFormatFail = `unsupported media type requested, only %v are available`
  46. )
  47. // InvalidContentType error for an invalid content type
  48. func InvalidContentType(value string, allowed []string) *Validation {
  49. values := make([]interface{}, 0, len(allowed))
  50. for _, v := range allowed {
  51. values = append(values, v)
  52. }
  53. return &Validation{
  54. code: http.StatusUnsupportedMediaType,
  55. Name: "Content-Type",
  56. In: "header",
  57. Value: value,
  58. Values: values,
  59. message: fmt.Sprintf(contentTypeFail, value, allowed),
  60. }
  61. }
  62. // InvalidResponseFormat error for an unacceptable response format request
  63. func InvalidResponseFormat(value string, allowed []string) *Validation {
  64. values := make([]interface{}, 0, len(allowed))
  65. for _, v := range allowed {
  66. values = append(values, v)
  67. }
  68. return &Validation{
  69. code: http.StatusNotAcceptable,
  70. Name: "Accept",
  71. In: "header",
  72. Value: value,
  73. Values: values,
  74. message: fmt.Sprintf(responseFormatFail, allowed),
  75. }
  76. }