-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_util.go
86 lines (77 loc) · 2.34 KB
/
http_util.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package ddderr
import (
"net/http"
)
// HttpError is an RFC-compliant HTTP protocol problem object.
//
// For more information about the fields, please go to: https://datatracker.ietf.org/doc/html/rfc7807
type HttpError struct {
Type string `json:"type,omitempty"`
Title string `json:"title,omitempty"`
Status string `json:"status,omitempty"`
StatusCode int `json:"status_code,omitempty"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
}
// NewHttpError builds an HttpError from the given DDD error
func NewHttpError(errType, instance string, err error) HttpError {
if err == nil {
return HttpError{}
}
code := http.StatusInternalServerError
errHttpType := getHttpErrorType(errType, code)
customErr, ok := err.(Error)
if !ok {
return HttpError{
Type: errHttpType,
Title: err.Error(),
Status: http.StatusText(code),
StatusCode: code,
Detail: err.Error(),
Instance: instance,
}
}
code = GetHttpStatusCode(customErr)
errHttpType = getHttpErrorType(errType, code)
return HttpError{
Type: errHttpType,
Title: customErr.Title(),
Status: getHttpDddErrorStatus(customErr, code),
StatusCode: code,
Detail: customErr.Description(),
Instance: instance,
}
}
// retrieves a generic HTTP problem object type.
//
// For more information, go to: https://datatracker.ietf.org/doc/html/rfc7807#section-4.2
func getHttpErrorType(rootType string, status int) string {
if rootType != "" {
return rootType
}
return http.StatusText(status)
}
// retrieves a status name from an Error or a generic HTTP problem object type.
//
// For more information, go to: https://datatracker.ietf.org/doc/html/rfc7807#section-4.2
func getHttpDddErrorStatus(err Error, status int) string {
if statusName := err.Status(); statusName != "" {
return statusName
}
return http.StatusText(status)
}
// GetHttpStatusCode retrieves an HTTP status code from the given error
func GetHttpStatusCode(err Error) int {
switch {
case err.IsAlreadyExists():
return http.StatusConflict
case err.IsNotFound():
return http.StatusNotFound
case err.IsInvalidFormat() || err.IsRequired() || err.IsOutOfRange() || err.IsDomain():
return http.StatusBadRequest
case err.IsRemoteCall():
return http.StatusBadGateway
default:
return http.StatusInternalServerError
}
}