一个HTTP中间件:Recover

f2xc 9年前

Recover是一个HTTP中间件,能够捕捉任何panics并提供一个适当的错误响应。

适用于所有框架,支持原生http handler (eg. Echo, Goji).

安装

$ go get github.com/dre1080/recover

用法

package main    import (      "log"      "net/http"        "github.com/dre1080/recover"  )    var myPanicHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {      panic("you should not have a handler that just panics ;)")  })    func main() {      recovery := recover.New(&recover.Options{          Log: log.Print,      })        // recoveryWithDefaults := recovery.New(nil)        app := recovery(myPanicHandler)      http.ListenAndServe("0.0.0.0:3000", app)  }

Terminal

Terminal

HTML

HTML

JSON

JSON

Echo Example

...  func main() {      e := echo.New()      e.Use(recover.New(&recover.Options{          Log: log.Print,      }))        ...        e.Run(":3000")  }

Goji Example

...  func main() {      goji.Use(recover.New(&recover.Options{          Log: log.Print,      }))        ...        goji.Serve()  }

项目主页:http://www.open-open.com/lib/view/home/1443670589267