1
0
mirror of https://github.com/labstack/echo.git synced 2025-07-13 01:30:31 +02:00

Fixed Response#Before()

Implemented Response#After()

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana
2017-12-24 10:59:29 -08:00
parent b338075a0f
commit a028fd41fd

View File

@ -4,6 +4,7 @@ import (
"bufio" "bufio"
"net" "net"
"net/http" "net/http"
"strconv"
) )
type ( type (
@ -12,7 +13,9 @@ type (
// See: https://golang.org/pkg/net/http/#ResponseWriter // See: https://golang.org/pkg/net/http/#ResponseWriter
Response struct { Response struct {
echo *Echo echo *Echo
contentLength int64
beforeFuncs []func() beforeFuncs []func()
afterFuncs []func()
Writer http.ResponseWriter Writer http.ResponseWriter
Status int Status int
Size int64 Size int64
@ -40,6 +43,12 @@ func (r *Response) Before(fn func()) {
r.beforeFuncs = append(r.beforeFuncs, fn) r.beforeFuncs = append(r.beforeFuncs, fn)
} }
// After registers a function which is called just after the response is written.
// If the `Content-Length` is unknown, none of the after function is executed.
func (r *Response) After(fn func()) {
r.afterFuncs = append(r.afterFuncs, fn)
}
// WriteHeader sends an HTTP response header with status code. If WriteHeader is // WriteHeader sends an HTTP response header with status code. If WriteHeader is
// not called explicitly, the first call to Write will trigger an implicit // not called explicitly, the first call to Write will trigger an implicit
// WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly // WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly
@ -55,6 +64,7 @@ func (r *Response) WriteHeader(code int) {
r.Status = code r.Status = code
r.Writer.WriteHeader(code) r.Writer.WriteHeader(code)
r.Committed = true r.Committed = true
r.contentLength, _ = strconv.ParseInt(r.Header().Get(HeaderContentLength), 10, 0)
} }
// Write writes the data to the connection as part of an HTTP reply. // Write writes the data to the connection as part of an HTTP reply.
@ -64,6 +74,11 @@ func (r *Response) Write(b []byte) (n int, err error) {
} }
n, err = r.Writer.Write(b) n, err = r.Writer.Write(b)
r.Size += int64(n) r.Size += int64(n)
if r.Size == r.contentLength {
for _, fn := range r.afterFuncs {
fn()
}
}
return return
} }
@ -91,6 +106,9 @@ func (r *Response) CloseNotify() <-chan bool {
} }
func (r *Response) reset(w http.ResponseWriter) { func (r *Response) reset(w http.ResponseWriter) {
r.contentLength = 0
r.beforeFuncs = nil
r.afterFuncs = nil
r.Writer = w r.Writer = w
r.Size = 0 r.Size = 0
r.Status = http.StatusOK r.Status = http.StatusOK