0

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

4

1 回答 1

1

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

我想不出在中间件中做到这一点的方法,因为中间件只是作用于请求/响应和http.HandlerFunc(s)。

于 2017-03-23T16:25:18.187 回答