...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package errors
16
17 import (
18 "encoding/json"
19 "fmt"
20 "net/http"
21 )
22
23
24 type Validation struct {
25 code int32
26 Name string
27 In string
28 Value interface{}
29 message string
30 Values []interface{}
31 }
32
33 func (e *Validation) Error() string {
34 return e.message
35 }
36
37
38 func (e *Validation) Code() int32 {
39 return e.code
40 }
41
42
43 func (e Validation) MarshalJSON() ([]byte, error) {
44 return 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
55 func (e *Validation) ValidateName(name string) *Validation {
56 if name != "" {
57 if e.Name == "" {
58 e.Name = name
59 e.message = name + e.message
60 } else {
61 e.Name = name + "." + e.Name
62 e.message = name + "." + e.message
63 }
64 }
65 return e
66 }
67
68 const (
69 contentTypeFail = `unsupported media type %q, only %v are allowed`
70 responseFormatFail = `unsupported media type requested, only %v are available`
71 )
72
73
74 func InvalidContentType(value string, allowed []string) *Validation {
75 values := make([]interface{}, 0, len(allowed))
76 for _, v := range allowed {
77 values = append(values, v)
78 }
79 return &Validation{
80 code: http.StatusUnsupportedMediaType,
81 Name: "Content-Type",
82 In: "header",
83 Value: value,
84 Values: values,
85 message: fmt.Sprintf(contentTypeFail, value, allowed),
86 }
87 }
88
89
90 func InvalidResponseFormat(value string, allowed []string) *Validation {
91 values := make([]interface{}, 0, len(allowed))
92 for _, v := range allowed {
93 values = append(values, v)
94 }
95 return &Validation{
96 code: http.StatusNotAcceptable,
97 Name: "Accept",
98 In: "header",
99 Value: value,
100 Values: values,
101 message: fmt.Sprintf(responseFormatFail, allowed),
102 }
103 }
104
View as plain text