Fixes wrap around http.ResponseWriter

This commit is contained in:
Manu Mtz-Almeida 2014-07-04 00:01:28 +02:00
parent b8053b284d
commit d42aa6d868
3 changed files with 55 additions and 4 deletions

View File

@ -286,6 +286,10 @@ func Logger() gin.HandlerFunc {
// after request // after request
latency := time.Since(t) latency := time.Since(t)
log.Print(latency) log.Print(latency)
// access the status we are sending
status := c.Writer.Status()
log.Println(status)
} }
} }

8
gin.go
View File

@ -40,7 +40,7 @@ type (
// manage the flow, validate the JSON of a request and render a JSON response for example. // manage the flow, validate the JSON of a request and render a JSON response for example.
Context struct { Context struct {
Req *http.Request Req *http.Request
Writer http.ResponseWriter Writer ResponseWriter
Keys map[string]interface{} Keys map[string]interface{}
Errors ErrorMsgs Errors ErrorMsgs
Params httprouter.Params Params httprouter.Params
@ -92,7 +92,7 @@ func NewWithConfig(config Config) *Engine {
// Fill it with empty contexts // Fill it with empty contexts
for i := 0; i < config.Preallocated; i++ { for i := 0; i < config.Preallocated; i++ {
engine.cache <- &Context{Engine: engine} engine.cache <- &Context{Engine: engine, Writer: &responseWriter{}}
} }
return engine return engine
} }
@ -171,7 +171,7 @@ func (engine *Engine) Run(addr string) {
func (engine *Engine) createContext(w http.ResponseWriter, req *http.Request, params httprouter.Params, handlers []HandlerFunc) *Context { func (engine *Engine) createContext(w http.ResponseWriter, req *http.Request, params httprouter.Params, handlers []HandlerFunc) *Context {
select { select {
case c := <-engine.cache: case c := <-engine.cache:
c.Writer = w c.Writer.reset(w)
c.Req = req c.Req = req
c.Params = params c.Params = params
c.handlers = handlers c.handlers = handlers
@ -180,7 +180,7 @@ func (engine *Engine) createContext(w http.ResponseWriter, req *http.Request, pa
return c return c
default: default:
return &Context{ return &Context{
Writer: w, Writer: &responseWriter{w, -1, false},
Req: req, Req: req,
Params: params, Params: params,
handlers: handlers, handlers: handlers,

47
response_writer.go Normal file
View File

@ -0,0 +1,47 @@
package gin
import (
"net/http"
)
type (
ResponseWriter interface {
http.ResponseWriter
Status() int
Written() bool
// private
reset(http.ResponseWriter)
setStatus(int)
}
responseWriter struct {
http.ResponseWriter
status int
written bool
}
)
func (w *responseWriter) reset(writer http.ResponseWriter) {
w.ResponseWriter = writer
w.status = 0
w.written = false
}
func (w *responseWriter) setStatus(code int) {
w.status = code
}
func (w *responseWriter) WriteHeader(code int) {
w.status = code
w.written = true
w.ResponseWriter.WriteHeader(code)
}
func (w *responseWriter) Status() int {
return w.status
}
func (w *responseWriter) Written() bool {
return w.written
}