podman
103 строки · 2.6 Кб
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
15package errors
16
17import (
18"encoding/json"
19"fmt"
20"net/http"
21)
22
23// Validation represents a failure of a precondition
24type Validation struct {
25code int32
26Name string
27In string
28Value interface{}
29message string
30Values []interface{}
31}
32
33func (e *Validation) Error() string {
34return e.message
35}
36
37// Code the error code
38func (e *Validation) Code() int32 {
39return e.code
40}
41
42// MarshalJSON implements the JSON encoding interface
43func (e Validation) MarshalJSON() ([]byte, error) {
44return json.Marshal(map[string]interface{}{
45"code": e.code,
46"message": e.message,
47"in": e.In,
48"name": e.Name,
49"value": e.Value,
50"values": e.Values,
51})
52}
53
54// ValidateName sets the name for a validation or updates it for a nested property
55func (e *Validation) ValidateName(name string) *Validation {
56if name != "" {
57if e.Name == "" {
58e.Name = name
59e.message = name + e.message
60} else {
61e.Name = name + "." + e.Name
62e.message = name + "." + e.message
63}
64}
65return e
66}
67
68const (
69contentTypeFail = `unsupported media type %q, only %v are allowed`
70responseFormatFail = `unsupported media type requested, only %v are available`
71)
72
73// InvalidContentType error for an invalid content type
74func InvalidContentType(value string, allowed []string) *Validation {
75values := make([]interface{}, 0, len(allowed))
76for _, v := range allowed {
77values = append(values, v)
78}
79return &Validation{
80code: http.StatusUnsupportedMediaType,
81Name: "Content-Type",
82In: "header",
83Value: value,
84Values: values,
85message: fmt.Sprintf(contentTypeFail, value, allowed),
86}
87}
88
89// InvalidResponseFormat error for an unacceptable response format request
90func InvalidResponseFormat(value string, allowed []string) *Validation {
91values := make([]interface{}, 0, len(allowed))
92for _, v := range allowed {
93values = append(values, v)
94}
95return &Validation{
96code: http.StatusNotAcceptable,
97Name: "Accept",
98In: "header",
99Value: value,
100Values: values,
101message: fmt.Sprintf(responseFormatFail, allowed),
102}
103}
104