feat: support sse ignore timeout (#2041)

Co-authored-by: Kevin Wan <wanjunfeng@gmail.com>
master
chen quan 9 months ago committed by GitHub
parent 0f1d4c6bca
commit 28cb2c5804
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -24,6 +24,8 @@ const (
reason = "Request Timeout" reason = "Request Timeout"
headerUpgrade = "Upgrade" headerUpgrade = "Upgrade"
valueWebsocket = "websocket" valueWebsocket = "websocket"
headerAccept = "Accept"
valueSSE = "text/event-stream"
) )
// TimeoutHandler returns the handler with given timeout. // TimeoutHandler returns the handler with given timeout.
@ -56,7 +58,9 @@ func (h *timeoutHandler) errorBody() string {
} }
func (h *timeoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { func (h *timeoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Header.Get(headerUpgrade) == valueWebsocket { if r.Header.Get(headerUpgrade) == valueWebsocket ||
// Server-Sent Event ignore timeout.
r.Header.Get(headerAccept) == valueSSE {
h.handler.ServeHTTP(w, r) h.handler.ServeHTTP(w, r)
return return
} }
@ -110,7 +114,7 @@ func (h *timeoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} else { } else {
w.WriteHeader(http.StatusServiceUnavailable) w.WriteHeader(http.StatusServiceUnavailable)
} }
io.WriteString(w, h.errorBody()) _, _ = io.WriteString(w, h.errorBody())
}) })
tw.timedOut = true tw.timedOut = true
} }

@ -156,6 +156,22 @@ func TestTimeoutPanic(t *testing.T) {
}) })
} }
func TestTimeoutSSE(t *testing.T) {
timeoutHandler := TimeoutHandler(time.Millisecond)
handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Millisecond * 10)
r.Header.Set("Content-Type", "text/event-stream")
r.Header.Set("Cache-Control", "no-cache")
r.Header.Set("Connection", "keep-alive")
r.Header.Set("Transfer-Encoding", "chunked")
}))
req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
req.Header.Set(headerAccept, valueSSE)
resp := httptest.NewRecorder()
handler.ServeHTTP(resp, req)
assert.Equal(t, http.StatusOK, resp.Code)
}
func TestTimeoutWebsocket(t *testing.T) { func TestTimeoutWebsocket(t *testing.T) {
timeoutHandler := TimeoutHandler(time.Millisecond) timeoutHandler := TimeoutHandler(time.Millisecond)
handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

Loading…
Cancel
Save