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 := 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/

相关文章:

go - 回历日期到 golang 中的公历日期

mongodb - 发送分块文件以保存在 mongodb 中

go - 将结构转换为基类

go - negroni/gorilla mux 的子路由器问题

go - 将参数传递给 Negroni 中间件

json - 在 http 响应中将任意字符串编码为 JSON

go - 使用 Gorilla MUX 和 Negroni 的子路由中间件

在 GO (GO1) 中构建多个文件

go - 导入Golang代码的本地文件夹