forked from nytimes/gizmo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware_go17.go
74 lines (64 loc) · 1.85 KB
/
middleware_go17.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
// +build go1.7
package server
import (
"bytes"
"context"
"encoding/json"
"net/http"
)
// JSONContextToHTTP is a middleware func to convert a ContextHandler an http.Handler.
func JSONContextToHTTP(ep JSONContextEndpoint) ContextHandler {
return ContextHandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
if r.Body != nil {
defer func() {
if err := r.Body.Close(); err != nil {
}
}()
}
// it's JSON, so always set that content type
w.Header().Set("Content-Type", jsonContentType)
// prepare to grab the response from the ep
var b bytes.Buffer
encoder := json.NewEncoder(&b)
// call the func and return err or not
code, res, err := ep(ctx, r)
w.WriteHeader(code)
if err != nil {
res = err
}
err = encoder.Encode(res)
if err != nil {
LogWithFields(r).Error("unable to JSON encode response: ", err)
}
if _, err := w.Write(b.Bytes()); err != nil {
LogWithFields(r).Warn("unable to write response: ", err)
}
})
}
// ContextToHTTP is a middleware func to convert a ContextHandler an http.Handler.
func ContextToHTTP(ep ContextHandler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ep.ServeHTTPContext(r.Context(), w, r)
})
}
// WithCloseHandler returns a Handler cancelling the context when the client
// connection close unexpectedly.
func WithCloseHandler(h ContextHandler) ContextHandler {
return ContextHandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
// Cancel the context if the client closes the connection
if wcn, ok := w.(http.CloseNotifier); ok {
var cancel context.CancelFunc
ctx, cancel = context.WithCancel(ctx)
defer cancel()
notify := wcn.CloseNotify()
go func() {
select {
case <-notify:
cancel()
case <-ctx.Done():
}
}()
}
h.ServeHTTPContext(ctx, w, r)
})
}