mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-14 20:22:20 +08:00
Added Before function to ResponseWriter.
This allows middleware to have a function get called right before ResponseWriter has been written to. It can be used to set headers or do other necessary things before a response has been written.
This commit is contained in:
parent
c3abaf9afc
commit
c4d81efeca
@ -9,6 +9,8 @@ type (
|
||||
http.ResponseWriter
|
||||
Status() int
|
||||
Written() bool
|
||||
// Before allows for a function to be called before the ResponseWriter has been written to.
|
||||
Before(BeforeFunc)
|
||||
|
||||
// private
|
||||
setStatus(int)
|
||||
@ -16,15 +18,19 @@ type (
|
||||
|
||||
responseWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
written bool
|
||||
status int
|
||||
written bool
|
||||
beforeFuncs []BeforeFunc
|
||||
}
|
||||
|
||||
BeforeFunc func(ResponseWriter)
|
||||
)
|
||||
|
||||
func (w *responseWriter) reset(writer http.ResponseWriter) {
|
||||
w.ResponseWriter = writer
|
||||
w.status = 0
|
||||
w.written = false
|
||||
w.beforeFuncs = w.beforeFuncs[:0]
|
||||
}
|
||||
|
||||
func (w *responseWriter) setStatus(code int) {
|
||||
@ -32,6 +38,7 @@ func (w *responseWriter) setStatus(code int) {
|
||||
}
|
||||
|
||||
func (w *responseWriter) WriteHeader(code int) {
|
||||
w.callBefore()
|
||||
w.status = code
|
||||
w.written = true
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
@ -44,3 +51,13 @@ func (w *responseWriter) Status() int {
|
||||
func (w *responseWriter) Written() bool {
|
||||
return w.written
|
||||
}
|
||||
|
||||
func (w *responseWriter) Before(before BeforeFunc) {
|
||||
w.beforeFuncs = append(w.beforeFuncs, before)
|
||||
}
|
||||
|
||||
func (w *responseWriter) callBefore() {
|
||||
for i := len(w.beforeFuncs) - 1; i >= 0; i-- {
|
||||
w.beforeFuncs[i](w)
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user