英文:
Can I use my function as `negroni` middleware
问题
我有一个函数,我将其用作每个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
中间件函数之间传递数据吗?
英文:
I have a function which I use as wrapper for every GET request:
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:
router.HandleFunc("/rss/unread/{rss_type}",
controllers.WrapHandler(controllers.GetUnreadRssFeeds))
example:
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
}
Now I need wrap each request in the router: controllers.WrapHandler(controllers.GetUnreadRssFeeds)
. I am looking the way to avoid it.
Can I transform my WrapHandler
to use it as negroni
middleware ? Is there a way to pass data between negroni
middleware functions ?
答案1
得分: 1
你在使用WrapHandler
作为negroni中间件时需要克服的障碍是,你的WrapHandler
实际上是一个适配器,而不是一个包装器。你正在将一个非http.HandlerFunc
转换为http.HandlerFunc
。
我无法想到一种在中间件中实现这个的方法,因为中间件只对请求/响应和http.HandlerFunc
进行操作。
英文:
The hurdle you'll have to cross with using your WrapHandler
as negroni middleware is that your WrapHandler
is actually an adaptor, not a wrapper. You're taking a non-http.HandlerFunc
and converting it to a http.HandlerFunc
.
I can't think of a way to do that in middleware, because middleware just acts on the request/response and the http.HandlerFunc
(s).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论