为了确保在所有请求中正确处理错误结果,我正在实现一个自定义处理程序,如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)
}发布于 2015-08-30 01:27:43
如果您想要的话,可以编写r.Handle的包装器。您不能在全局范围内使用Negroni,因为并不是所有您使用的中间件都假定您的handler类型。
例如:
// Named to make the example clear.
func wrap(r *mux.Router, pattern string, h handler) *mux.Route {
return r.Handle(pattern, h)
}
func index(w http.ResponseWriter, r *http.Request) error {
io.WriteString(w, "Hello")
return nil
}
func main() {
r := mux.NewRouter()
wrap(r, "/", index)
http.ListenAndServe(":8000", r)
}我认为,这并不比显式类型转换处理程序(这很明显,如果有点重复)或将处理程序类型转换为结构好得多。后者可以扩展为包含线程安全字段(您的DB池、app config等),然后您可以显式地与每个处理程序一起传递这些字段。
在现实中,您当前的路由器代码仍然清晰且易于阅读,并且(对其他人而言)您的处理程序的基础是哪种类型。
https://stackoverflow.com/questions/32286407
复制相似问题