Skip to content

Instantly share code, notes, and snippets.

@luza
Last active February 10, 2023 08:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luza/dca5936637f525848d67e49e21820f93 to your computer and use it in GitHub Desktop.
Save luza/dca5936637f525848d67e49e21820f93 to your computer and use it in GitHub Desktop.
// instrumentedWriter is a wrapper around gin.ResponseWriter that calls
// BeforeWriteHeaderCallback before response headers is written.
type instrumentedWriter struct {
gin.ResponseWriter
BeforeWriteHeaderCallback func()
}
func (w *instrumentedWriter) Write(data []byte) (int, error) {
w.runBeforeWriteHeaderCallbackOnce()
return w.ResponseWriter.Write(data)
}
func (w *instrumentedWriter) WriteString(s string) (int, error) {
w.runBeforeWriteHeaderCallbackOnce()
return w.ResponseWriter.WriteString(s)
}
func (w *instrumentedWriter) Flush() {
w.runBeforeWriteHeaderCallbackOnce()
w.ResponseWriter.Flush()
}
func (w *instrumentedWriter) runBeforeWriteHeaderCallbackOnce() {
if w.BeforeWriteHeaderCallback == nil {
return
}
w.BeforeWriteHeaderCallback()
w.BeforeWriteHeaderCallback = nil
}
// how to use
g.POST("/path", function (c gin.Context) {
c.Writer = &instrumentedWriter{
ResponseWriter: c.Writer,
BeforeWriteHeaderCallback: func() {
// your code to be called before headers is sent
},
}
// your request processing code
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment