douran7929 2017-03-23 13:59 采纳率: 100%
浏览 46
已采纳

我可以使用我的功能作为“ 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条回答 默认 最新

  • douhandie6615 2017-03-23 16:25
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch