-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpx.go
More file actions
207 lines (166 loc) · 4.98 KB
/
httpx.go
File metadata and controls
207 lines (166 loc) · 4.98 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package httpx
import (
"context"
"fmt"
"net/http"
"github.com/pkg/errors"
)
type (
HTTPHandlerExt func(http.ResponseWriter, *http.Request) error
AdapterFunc func(http.ResponseWriter, *http.Request, error)
HandlerAdapter struct {
InternalErrs AdapterFunc
ClientErrs AdapterFunc
UnauthorizedErr AdapterFunc
// OnError is called for every handler error or panic before the response is sent.
// Use this for logging, metrics, or error reporting.
OnError func(r *http.Request, err error)
}
Error interface {
error
GetStatusCode() int
}
AppError struct {
Err error
StatusCode int
}
Renderer interface {
Render500(ctx context.Context, w http.ResponseWriter, errInfo *ErrorInfo)
RenderAppError(ctx context.Context, w http.ResponseWriter, appErr AppError)
}
AppConfig interface {
IsDevelopment() bool
ReportError(ctx context.Context, err error)
GetRenderer() Renderer
}
ErrorInfo struct {
Message string `json:"message,omitempty"`
Cause string `json:"cause,omitempty"`
Stack string `json:"stack,omitempty"`
}
)
func BadRequestError(content string, params ...interface{}) AppError {
return StatusError(http.StatusBadRequest, content, params...)
}
func NotFoundError(content string, params ...interface{}) AppError {
return StatusError(http.StatusNotFound, content, params...)
}
func UnauthorizedError(content string, params ...interface{}) AppError {
return StatusError(http.StatusUnauthorized, content, params...)
}
func ForbiddenError(content string, params ...interface{}) AppError {
return StatusError(http.StatusForbidden, content, params...)
}
func ConflictError(content string, params ...interface{}) AppError {
return StatusError(http.StatusConflict, content, params...)
}
func UnprocessableEntityError(content string, params ...interface{}) AppError {
return StatusError(http.StatusUnprocessableEntity, content, params...)
}
func StatusError(statusCode int, content string, params ...interface{}) AppError {
return AppError{
Err: fmt.Errorf(content, params...),
StatusCode: statusCode,
}
}
func (e AppError) Error() string {
return e.Err.Error()
}
func (e AppError) GetStatusCode() int {
return e.StatusCode
}
func defaultAppError(w http.ResponseWriter, req *http.Request, err error) {
if e, ok := err.(AppError); ok {
http.Error(w, err.Error(), e.GetStatusCode())
return
}
http.Error(w, "Bad Request", http.StatusBadRequest)
}
func defaultInternalError(w http.ResponseWriter, req *http.Request, err error) {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
func InternalErrorsHandler(config AppConfig) func(http.ResponseWriter, *http.Request, error) {
return func(w http.ResponseWriter, req *http.Request, err error) {
var errInfo *ErrorInfo
w.WriteHeader(http.StatusInternalServerError)
config.ReportError(req.Context(), err)
if config.IsDevelopment() {
errInfo = &ErrorInfo{
Message: fmt.Sprintf("%s", err),
}
// Unwrap the error to get the root cause, if any
if cause := errors.Unwrap(err); cause != nil {
errInfo.Cause = cause.Error()
}
// Check if the error has a stack trace
type stackTracer interface {
StackTrace() errors.StackTrace
}
if stackErr, ok := err.(stackTracer); ok {
st := stackErr.StackTrace()
errInfo.Stack = fmt.Sprintf("%+v", st)
}
}
// Use the Renderer to render the 500 error response
config.GetRenderer().Render500(context.Background(), w, errInfo)
}
}
func NewDefaultHandlerAdapter(config AppConfig) *HandlerAdapter {
return &HandlerAdapter{
InternalErrs: InternalErrorsHandler(config),
ClientErrs: defaultAppError,
UnauthorizedErr: nil,
}
}
func RecoverMiddleware(adapter *HandlerAdapter, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
var err error
switch x := rec.(type) {
case string:
err = fmt.Errorf(x)
case error:
err = x
default:
err = fmt.Errorf("unknown panic")
}
if adapter.OnError != nil {
adapter.OnError(r, err)
}
adapter.InternalErrs(w, r, err)
}
}()
next.ServeHTTP(w, r)
})
}
func (a *HandlerAdapter) Handle(h HTTPHandlerExt) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
if err := h(w, req); err != nil {
// Call OnError callback first (for logging/reporting)
if a.OnError != nil {
a.OnError(req, err)
}
switch e := err.(type) {
case AppError:
if e.StatusCode == http.StatusUnauthorized && a.UnauthorizedErr != nil {
a.UnauthorizedErr(w, req, e)
return
}
if a.ClientErrs != nil {
a.ClientErrs(w, req, err)
return
}
// Use default AppError handler if no ClientErrs adapter is provided
defaultAppError(w, req, err)
default:
if a.InternalErrs != nil {
a.InternalErrs(w, req, err)
return
}
// Use default internal error handler if no InternalErrs adapter is provided
defaultInternalError(w, req, err)
}
}
}
}