为了确保在所有请求中正确处理错误结果,我正在实现一个自定义处理程序,如http://blog.golang.org/error-handling-and-go中所述。因此,处理程序不仅可以接受w http.ResponseWriter, r *http.Request参数,还可以选择返回一个error.
我正在使用 Negroni,想知道是否可以设置一次以将所有请求包装到其中,或者是否始终必须按照以下示例中的handler每个请求进行设置?//foo
type handler func(w http.ResponseWriter, r *http.Request) error
// ServeHTTP checks for error results and handles them globally
func (fn handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := fn(w, r); err != nil {
http.Error(w, err, http.StatusInternalServerError)
}
}
// Index matches the `handler` type and returns an error
func Index(w http.ResponseWriter, r *http.Request) error {
return errors.New("something went wrong")
}
func main() {
router := mux.NewRouter()
// note how `Index` is wrapped into `handler`. Is there a way to
// make this global? Or will the handler(fn) pattern be required
// for every request?
router.Handle("/", handler(Index)).Methods("GET")
router.Handle("/foo", handler(Index)).Methods("GET")
n := negroni.New(
negroni.NewRecovery(),
negroni.NewLogger(),
negroni.Wrap(router),
)
port := os.Getenv("PORT")
n.Run(":" + port)
}