Improves Recovery middleware:

- request context
- red colouring
This commit is contained in:
Manu Mtz.-Almeida 2016-01-26 18:35:56 +01:00
parent 2fc2a3e782
commit 7afb3238a3
2 changed files with 5 additions and 3 deletions

2
gin.go
View File

@ -113,7 +113,7 @@ func New() *Engine {
// Default returns an Engine instance with the Logger and Recovery middleware already attached. // Default returns an Engine instance with the Logger and Recovery middleware already attached.
func Default() *Engine { func Default() *Engine {
engine := New() engine := New()
engine.Use(Recovery(), Logger()) engine.Use(Logger(), Recovery())
return engine return engine
} }

View File

@ -10,6 +10,7 @@ import (
"io" "io"
"io/ioutil" "io/ioutil"
"log" "log"
"net/http/httputil"
"runtime" "runtime"
) )
@ -28,14 +29,15 @@ func Recovery() HandlerFunc {
func RecoveryWithWriter(out io.Writer) HandlerFunc { func RecoveryWithWriter(out io.Writer) HandlerFunc {
var logger *log.Logger var logger *log.Logger
if out != nil { if out != nil {
logger = log.New(out, "", log.LstdFlags) logger = log.New(out, "\n\n\x1b[31m", log.LstdFlags)
} }
return func(c *Context) { return func(c *Context) {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
if logger != nil { if logger != nil {
stack := stack(3) stack := stack(3)
logger.Printf("Panic recovery -> %s\n%s\n", err, stack) httprequest, _ := httputil.DumpRequest(c.Request, false)
logger.Printf("[Recovery] panic recovered:\n%s\n%s\n%s %s", string(httprequest), err, stack, reset)
} }
c.AbortWithStatus(500) c.AbortWithStatus(500)
} }