chi
chi copied to clipboard
middleware: add method to WrapResponseWriter for getting response writing time
This PR introduces a new method, ElapsedWriteTime(), to the middleware.WrapResponseWriter. This addition is particularly useful in scenarios where clients are slow or responses are large, necessitating a measure of the time taken to write the response.
Please note, that this change may break backward compatibility. An alternative could be to introduce a separate interface containing only this new method. However, this would require developers to perform type assertions in the client code, which may reduce clarity. So, your feedback on this approach is appreciated.
Perhaps a better approach would be to introduce a hook on first written byte, e.g.
start := time.Now()
var firstByteWritten time.Time
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
ww.OnWriteHeader(func(statusCode int) {
firstByteWritten = time.Now()
})
next.ServeHTTP(ww, r.WithContext(ctx))
elapsed := time.Since(start)
writeElapsed := time.Since(firstByteWritten)
And maybe we could generalize this even further. Thoughts?