Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

middleware: add method to WrapResponseWriter for getting response writing time #890

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

vasayxtx
Copy link
Contributor

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 vasayxtx force-pushed the wrap-response-writer-elapsed-time branch from 461ac32 to 1bfa1de Compare December 28, 2023 20:55
Copy link
Contributor

@VojtechVitek VojtechVitek left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the contribution! I think it's a cool feature and I see nice use-cases for telemetry.

However, I think it should be an opt-in feature, as I'm seeing some performance issues with the current approach.

@@ -91,6 +103,7 @@ func (b *basicWriter) Write(buf []byte) (int, error) {
err = err2
}
}
b.elapsedTime += time.Since(startTime)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This feels ineffective.

This calls time.Since() on each .Write() invocation, which may cause Go runtime to get the current time from the OS/kernel.

@VojtechVitek
Copy link
Contributor

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants