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

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

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历