Last active
February 10, 2023 08:45
-
-
Save luza/dca5936637f525848d67e49e21820f93 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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