-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
98 lines (92 loc) · 2.34 KB
/
http.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
87
88
89
90
91
92
93
94
95
96
97
98
package aerrors
import (
"errors"
"net/http"
)
type HTTPCoder interface {
HTTPCode() int
}
// nolint:gocyclo
func (err Code) HTTPCode() int {
switch err {
// GRPC Errors
case ErrOK:
return http.StatusOK
case ErrCanceled:
return http.StatusRequestTimeout
case ErrUnknown:
return http.StatusNotExtended
case ErrInvalidArgument:
return http.StatusBadRequest
case ErrDeadlineExceeded:
return http.StatusGatewayTimeout
case ErrNotFound:
return http.StatusNotFound
case ErrAlreadyExists:
return http.StatusConflict
case ErrPermissionDenied:
return http.StatusForbidden
case ErrResourceExhausted:
return http.StatusTooManyRequests
case ErrFailedPrecondition:
return http.StatusBadRequest
case ErrAborted:
return http.StatusConflict
case ErrOutOfRange:
return http.StatusUnprocessableEntity
case ErrUnimplemented:
return http.StatusNotImplemented
case ErrInternal:
return http.StatusInternalServerError
case ErrUnavailable:
return http.StatusServiceUnavailable
case ErrDataLoss:
return http.StatusInternalServerError
case ErrUnauthenticated:
return http.StatusUnauthorized
// HTTP Errors
case ErrBadRequest:
return http.StatusBadRequest
case ErrUnauthorized:
return http.StatusUnauthorized
case ErrForbidden:
return http.StatusForbidden
case ErrMethodNotAllowed:
return http.StatusMethodNotAllowed
case ErrRequestTimeout:
return http.StatusRequestTimeout
case ErrConflict:
return http.StatusConflict
case ErrImATeapot:
return 418 // teapot support
case ErrUnprocessableEntity:
return http.StatusUnprocessableEntity
case ErrTooManyRequests:
return http.StatusTooManyRequests
case ErrUnavailableForLegalReasons:
return http.StatusUnavailableForLegalReasons
case ErrInternalServerError:
return http.StatusInternalServerError
case ErrNotImplemented:
return http.StatusNotImplemented
case ErrBadGateway:
return http.StatusBadGateway
case ErrServiceUnavailable:
return http.StatusServiceUnavailable
case ErrGatewayTimeout:
return http.StatusGatewayTimeout
default:
return http.StatusInternalServerError
}
}
// HTTPCode returns the HTTP status for the given error or http.StatusOK when nil or http.StatusNotExtended otherwise
func HTTPCode(err error) int {
if err == nil {
return ErrOK.HTTPCode()
}
var e HTTPCoder
if errors.As(err, &e) {
return e.HTTPCode()
}
return ErrUnknown.HTTPCode()
}