gpt4 book ai didi

go - 我可以将我的功能用作 `negroni` 中间件吗

转载 作者:数据小太阳 更新时间:2023-10-29 03:13:52 25 4
gpt4 key购买 nike

我有一个函数,我将其用作每个 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 中间件函数之间传递数据?

最佳答案

使用 WrapHandler 作为 negroni 中间件时,您必须跨越的障碍是您的 WrapHandler 实际上是一个适配器,而不是包装器。您正在将非 http.HandlerFunc 转换为 http.HandlerFunc

我想不出在中间件中执行此操作的方法,因为中间件仅作用于请求/响应和 http.HandlerFunc(s)。

关于go - 我可以将我的功能用作 `negroni` 中间件吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42978249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com