-
Notifications
You must be signed in to change notification settings - Fork 21
/
middleware.go
56 lines (49 loc) · 1.53 KB
/
middleware.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
package http
import (
"errors"
"net/http"
"strings"
"github.com/pace/bricks/http/jsonapi/runtime"
"github.com/pace/bricks/maintenance/log"
)
type jsonApiErrorWriter struct {
http.ResponseWriter
req *http.Request
statusCode int
hasErr bool
hasBytes bool
}
func (e *jsonApiErrorWriter) Write(b []byte) (int, error) {
if e.hasErr {
log.Req(e.req).Warn().Msgf("Error already sent, ignoring: %q", string(b))
return 0, nil
}
repliesJsonApi := e.Header().Get("Content-Type") == runtime.JSONAPIContentType
requestsJsonApi := e.req.Header.Get("Accept") == runtime.JSONAPIContentType
if e.statusCode >= 400 && requestsJsonApi && !repliesJsonApi {
if e.hasBytes {
log.Req(e.req).Warn().Msgf("Body already contains data from previous writes: ignoring: %q", string(b))
return 0, nil
}
e.hasErr = true
runtime.WriteError(e.ResponseWriter, e.statusCode, errors.New(strings.Trim(string(b), "\n")))
return 0, nil
}
n, err := e.ResponseWriter.Write(b)
if err == nil && n > 0 {
e.hasBytes = true
}
return n, err
}
func (e *jsonApiErrorWriter) WriteHeader(code int) {
e.statusCode = code
e.ResponseWriter.WriteHeader(code)
}
// JsonApiErrorWriterMiddleware is a middleware that wraps http.ResponseWriter
// such that it forces responses with status codes 4xx/5xx to have
// Content-Type: application/vnd.api+json
func JsonApiErrorWriterMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(&jsonApiErrorWriter{ResponseWriter: w, req: r}, r)
})
}