/
codec.go
57 lines (49 loc) · 1.26 KB
/
codec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package profilesvc
import (
"net/http"
"github.com/RussellLuo/kun/pkg/httpcodec"
"github.com/RussellLuo/kun/pkg/oas2"
)
type Codec struct {
httpcodec.JSON
}
func (c Codec) EncodeFailureResponse(w http.ResponseWriter, err error) error {
return c.JSON.EncodeSuccessResponse(w, codeFrom(err), map[string]string{
"error": err.Error(),
})
}
func codeFrom(err error) int {
switch err {
case ErrNotFound:
return http.StatusNotFound
case ErrAlreadyExists, ErrInconsistentIDs:
return http.StatusBadRequest
default:
return http.StatusInternalServerError
}
}
func NewCodecs() *httpcodec.DefaultCodecs {
return httpcodec.NewDefaultCodecs(Codec{})
}
func GetFailures(name string) map[error]interface{} {
switch name {
case "PostProfile":
return oas2.Errors(ErrAlreadyExists)
case "GetProfile", "DeleteProfile", "GetAddresses", "GetAddress", "DeleteAddress":
return oas2.Errors(ErrNotFound)
case "PutProfile":
return oas2.Errors(ErrInconsistentIDs)
case "PatchProfile":
return oas2.Errors(ErrInconsistentIDs, ErrNotFound)
case "PostAddress":
return oas2.Errors(ErrAlreadyExists, ErrNotFound)
default:
return nil
}
}
func NewSchema() *oas2.ResponseSchema {
return &oas2.ResponseSchema{
Codecs: NewCodecs(),
GetFailuresFunc: GetFailures,
}
}