forked from go-chi/chi
/
closenotify.go
43 lines (35 loc) · 1.08 KB
/
closenotify.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
package middleware
import (
"net/http"
"github.com/pressly/chi"
"golang.org/x/net/context"
)
// StatusClientClosedRequest represents a 499 Client Closed Request (Nginx) HTTP status.
// See: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
const StatusClientClosedRequest = 499
// CloseNotify is a middleware that cancels ctx when the underlying
// connection has gone away. It can be used to cancel long operations
// on the server when the client disconnects before the response is ready.
func CloseNotify(next chi.Handler) chi.Handler {
fn := func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
cn, ok := w.(http.CloseNotifier)
if !ok {
panic("middleware.CloseNotify expects http.ResponseWriter to implement http.CloseNotifier interface")
}
closeNotifyCh := cn.CloseNotify()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
select {
case <-ctx.Done():
return
case <-closeNotifyCh:
cancel()
w.WriteHeader(StatusClientClosedRequest)
return
}
}()
next.ServeHTTPC(ctx, w, r)
}
return chi.HandlerFunc(fn)
}