-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontext_handler.go
More file actions
37 lines (34 loc) · 919 Bytes
/
context_handler.go
File metadata and controls
37 lines (34 loc) · 919 Bytes
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
package middleware
import (
"context"
"net/http"
)
// StatusNoResponse is returned when request is canceled
const StatusNoResponse = 444
// ContextHandler reads from context.Done channel to handle deadline/timeout
func ContextHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
processed := make(chan struct{})
go func() {
defer close(processed)
next.ServeHTTP(w, r)
}()
select {
case <-r.Context().Done():
switch r.Context().Err() {
case nil:
// do nothing
case context.Canceled:
http.Error(w, r.Context().Err().Error(), StatusNoResponse)
case context.DeadlineExceeded:
http.Error(w, r.Context().Err().Error(), http.StatusRequestTimeout)
default:
// handle unknown errors
http.Error(w, r.Context().Err().Error(), http.StatusInternalServerError)
}
return
case <-processed:
return
}
})
}