-
-
Notifications
You must be signed in to change notification settings - Fork 962
/
closenotify.go
42 lines (34 loc) · 1017 Bytes
/
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
package middleware
import (
"net/http"
"github.com/pressly/chi"
"golang.org/x/net/context"
)
// 499 Client Closed Request (Nginx)
// 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")
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
select {
case <-ctx.Done():
return
case <-cn.CloseNotify():
w.WriteHeader(StatusClientClosedRequest)
cancel()
return
}
}()
next.ServeHTTPC(ctx, w, r)
}
return chi.HandlerFunc(fn)
}