我有一个函数,用作每个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 := 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.WrapHandler(controllers.GetUnreadRssFeeds)。我正在寻找避免它的方法。
我可以将我的WrapHandler转换成negroni中间件吗?有没有一种在negroni中间件函数之间传递数据的方法?
发布于 2017-03-23 16:25:18
使用WrapHandler作为negroni中间件的障碍是,您的WrapHandler实际上是一个适配器,而不是包装器。你拿一个非http.HandlerFunc并把它转换成一个http.HandlerFunc。
我想不出在中间件中有什么方法可以做到这一点,因为中间件只对请求/响应和http.HandlerFunc起作用。
https://stackoverflow.com/questions/42978249
复制相似问题