mediamtx/internal/protocols/httpp/handler_write_timeout.go
Alessandro Ros 7634370818
Some checks failed
code_lint / go (push) Has been cancelled
code_lint / go_mod (push) Has been cancelled
code_lint / docs (push) Has been cancelled
code_lint / api_docs (push) Has been cancelled
code_test / test_64 (push) Has been cancelled
code_test / test_32 (push) Has been cancelled
code_test / test_e2e (push) Has been cancelled
add read and write timeouts in HTTP servers (#5056)
this prevents zombie connections from piling up.
2025-10-04 10:01:21 +02:00

44 lines
994 B
Go

package httpp
import (
"net/http"
"time"
)
type writeTimeoutWriter struct {
w http.ResponseWriter
rc *http.ResponseController
timeout time.Duration
}
func (w *writeTimeoutWriter) Header() http.Header {
return w.w.Header()
}
func (w *writeTimeoutWriter) Write(p []byte) (int, error) {
w.rc.SetWriteDeadline(time.Now().Add(w.timeout)) //nolint:errcheck
return w.w.Write(p)
}
func (w *writeTimeoutWriter) WriteHeader(statusCode int) {
w.rc.SetWriteDeadline(time.Now().Add(w.timeout)) //nolint:errcheck
w.w.WriteHeader(statusCode)
}
// apply write deadline before every Write() call.
// this allows to write long responses, splitted in chunks,
// without causing timeouts.
type handlerWriteTimeout struct {
h http.Handler
timeout time.Duration
}
func (h *handlerWriteTimeout) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ww := &writeTimeoutWriter{
w: w,
rc: http.NewResponseController(w),
timeout: h.timeout,
}
h.h.ServeHTTP(ww, r)
}