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