mirror of
https://github.com/zeromicro/go-zero.git
synced 2025-01-23 09:00:20 +08:00
feat: support sse ignore timeout (#2041)
Co-authored-by: Kevin Wan <wanjunfeng@gmail.com>
This commit is contained in:
parent
0f1d4c6bca
commit
28cb2c5804
@ -24,6 +24,8 @@ const (
|
||||
reason = "Request Timeout"
|
||||
headerUpgrade = "Upgrade"
|
||||
valueWebsocket = "websocket"
|
||||
headerAccept = "Accept"
|
||||
valueSSE = "text/event-stream"
|
||||
)
|
||||
|
||||
// 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) {
|
||||
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)
|
||||
return
|
||||
}
|
||||
@ -110,7 +114,7 @@ func (h *timeoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
} else {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}
|
||||
io.WriteString(w, h.errorBody())
|
||||
_, _ = io.WriteString(w, h.errorBody())
|
||||
})
|
||||
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) {
|
||||
timeoutHandler := TimeoutHandler(time.Millisecond)
|
||||
handler := timeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
Loading…
Reference in New Issue
Block a user