Go 我可以将我的函数用作“negroni”中间件吗
我有一个函数,用作每个GET请求的包装器:Go 我可以将我的函数用作“negroni”中间件吗,go,negroni,Go,Negroni,我有一个函数,用作每个GET请求的包装器: type HandlerFunc func(w http.ResponseWriter, req *http.Request) (interface{}, error) func WrapHandler(handler HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { data, err := ha
type HandlerFunc func(w http.ResponseWriter, req *http.Request) (interface{}, error)
func WrapHandler(handler HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
data, err := handler(w, req)
if err != nil {
log.Println(err)
w.WriteHeader(500)
} else {
w.Header().Add("Content-Type", "application/json")
resp, _ := json.Marshal(data)
w.Write(resp)
}
}
}
路由器:
router.HandleFunc("/rss/unread/{rss_type}",
controllers.WrapHandler(controllers.GetUnreadRssFeeds))
例如:
func GetUnreadRssFeeds(w http.ResponseWriter, r *http.Request) (interface{}, error) {
vars := mux.Vars(r)
rss_type, err := strconv.Atoi(vars["rss_type"])
feeds, err := (&postgres.FeedService{}).GetUnreadRssFeeds(rss_type)
return feeds, err
}
现在我需要在路由器中包装每个请求:controllers.WrapHandlercontrollers.GetUnreadRssFeeds。我正在寻找避免它的方法
我可以将我的WrapHandler转换为negroni中间件吗?有没有一种方法可以在negroni中间件函数之间传递数据?将WrapHandler用作negroni中间件需要克服的障碍是,WrapHandler实际上是适配器,而不是包装器。您正在获取一个非http.HandlerFunc并将其转换为http.HandlerFunc 我想不出在中间件中实现这一点的方法,因为中间件只作用于请求/响应和http.HandlerFuncs。可能的