@cryptotaxi247 / kubo / commits / c31e4f722

gateway: move context/close-notify wiring

License: MIT Signed-off-by: Lars Gierth <larsg@systemli.org>

Lars Gierth committed Sep 20, 2016 at 04:31 UTC c31e4f7226467ed8e703bfbff553ef1c2f586018
1 file changed +17 -16
core/corehttp/gateway_handler.go
+17 -16
@@ -60,6 +60,21 @@ func (i *gatewayHandler) newDagFromReader(r io.Reader) (node.Node, error) {
60
61 // TODO(btc): break this apart into separate handlers using a more expressive muxer
62 func (i *gatewayHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
63 + ctx, cancel := context.WithTimeout(i.node.Context(), time.Hour)
64 + // the hour is a hard fallback, we don't expect it to happen, but just in case
65 + defer cancel()
66 +
67 + if cn, ok := w.(http.CloseNotifier); ok {
68 + clientGone := cn.CloseNotify()
69 + go func() {
70 + select {
71 + case <-clientGone:
72 + case <-ctx.Done():
73 + }
74 + cancel()
75 + }()
76 + }
77 +
78 defer func() {
79 if r := recover(); r != nil {
80 log.Error("A panic occurred in the gateway handler!")
@@ -83,7 +98,7 @@ func (i *gatewayHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
98 }
99
100 if r.Method == "GET" || r.Method == "HEAD" {
86 - i.getOrHeadHandler(w, r)
101 + i.getOrHeadHandler(ctx, w, r)
102 return
103 }
104
@@ -113,21 +128,7 @@ func (i *gatewayHandler) optionsHandler(w http.ResponseWriter, r *http.Request)
128 i.addUserHeaders(w) // return all custom headers (including CORS ones, if set)
129 }
130
116 -func (i *gatewayHandler) getOrHeadHandler(w http.ResponseWriter, r *http.Request) {
117 - ctx, cancel := context.WithTimeout(i.node.Context(), time.Hour)
118 - // the hour is a hard fallback, we don't expect it to happen, but just in case
119 - defer cancel()
120 -
121 - if cn, ok := w.(http.CloseNotifier); ok {
122 - clientGone := cn.CloseNotify()
123 - go func() {
124 - select {
125 - case <-clientGone:
126 - case <-ctx.Done():
127 - }
128 - cancel()
129 - }()
130 - }
131 +func (i *gatewayHandler) getOrHeadHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
132
133 urlPath := r.URL.Path
134