-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhttp.go
More file actions
99 lines (91 loc) · 2.15 KB
/
http.go
File metadata and controls
99 lines (91 loc) · 2.15 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
package errors
import (
"net/http"
)
func httpStatusCode(eT errType) int {
status := http.StatusInternalServerError
switch eT {
case TypeValidation:
{
status = http.StatusUnprocessableEntity
}
case TypeInputBody:
{
status = http.StatusBadRequest
}
case TypeDuplicate:
{
status = http.StatusConflict
}
case TypeUnauthenticated:
{
status = http.StatusUnauthorized
}
case TypeUnauthorized:
{
status = http.StatusForbidden
}
case TypeEmpty:
{
status = http.StatusGone
}
case TypeNotFound:
{
status = http.StatusNotFound
}
case TypeMaximumAttempts:
{
status = http.StatusTooManyRequests
}
case TypeSubscriptionExpired:
{
status = http.StatusPaymentRequired
}
case TypeNotImplemented:
{
status = http.StatusNotImplemented
}
case TypeContextTimedout, TypeContextCancelled:
{
status = http.StatusRequestTimeout
}
}
return status
}
// HTTPStatusCodeMessage returns the appropriate HTTP status code, message, boolean for the error
// the boolean value is true if the error was of type *Error, false otherwise.
func HTTPStatusCodeMessage(err error) (int, string, bool) {
code, isErr := HTTPStatusCode(err)
msg, isErrMsg := Message(err)
if msg == "" {
msg = err.Error()
}
return code, msg, isErr && isErrMsg
}
// HTTPStatusCode returns appropriate HTTP response status code based on type of the error. The boolean
// is 'true' if the provided error is of type *Err. If joined error, boolean is true if all joined errors
// are of type *Error
// In case of joined errors, it'll return the status code of the last *Error
func HTTPStatusCode(err error) (int, bool) {
derr, _ := err.(*Error)
if derr != nil {
return httpStatusCode(derr.Type()), true
}
// Since TypeInternal is the default returned by getErrType, it is ignored.
if et := getErrType(err); et != TypeInternal {
return httpStatusCode(et), false
}
jerr, _ := err.(*joinError)
if jerr != nil {
elen := len(jerr.errs)
isErr := true
for i := elen - 1; i >= 0; i-- {
code, isE := HTTPStatusCode(jerr.errs[i])
isErr = isE && isErr
if isE {
return code, isErr
}
}
}
return http.StatusInternalServerError, false
}