chi icon indicating copy to clipboard operation
chi copied to clipboard

middleware: add method to WrapResponseWriter for getting response writing time

Open vasayxtx opened this issue 1 year ago • 1 comments

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.

vasayxtx avatar Dec 27 '23 20:12 vasayxtx

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?

VojtechVitek avatar Sep 18 '24 15:09 VojtechVitek