【问题标题】:How to pass a httprouter.Handle to a Prometheus http.HandleFunc如何将 httprouter.Handle 传递给 Prometheus http.HandleFunc
【发布时间】:2019-04-18 00:03:39
【问题描述】:

无法将 Prometheus 中间件传递到 httprouter 端点定义中。

我正在尝试将 Prometheus 中间件添加到我们的端点实现中。但是我们的端点正在使用第三方 mux 包,名为 httprouter。然后,当我尝试将此中间件添加到现有代码库中时,我找不到将两者集成在一起的好方法。


router := httprouter.New()
router.GET("/hello", r.Hello)

func (r configuration) Hello(w http.ResponseWriter, req *http.Request, ps httprouter.Params)

func InstrumentHandlerFunc(name string, handler http.HandlerFunc) http.HandlerFunc {
    counter := prometheus.NewCounterVec(
        do something...
    )

    duration := prometheus.NewHistogramVec(
        do something...
    )
    return promhttp.InstrumentHandlerDuration(duration,
        promhttp.InstrumentHandlerCounter(counter, handler))
}

我的问题是我无法将我的 prometheus 句柄作为参数传递给该 httprouter 端点函数

下面是我想做的:


func InstrumentHandlerFunc(name string, handler httprouter.Handle) httprouter.Handel {

}

router.Get("/hello", InstrumentHandlerFunc("/hello", r.Hello))

【问题讨论】:

  • 你到底想做什么?我不清楚你所说的“将两者结合在一起”是什么意思
  • 有没有可能我可以创建一个返回 httprouter.Handle 作为返回类型的 prometheus 中间件,并且我可以将 httprouter.Handle 作为函数参数之一传递。现在我只能创建常规的 prometheus http.HandleFunc 这种处理函数。
  • docs中声明路由器本身实现了http.Handler接口。所以你可以使用router.HandleFunc()并传递http.HandlerFunc()

标签: go prometheus httprouter


【解决方案1】:

如果你想在同一个项目中同时使用它们,你可以通过一个简单的方法来监听不同的ports来达到同样的效果

router := httprouter.New()
// register prometheus exporter 
go func() {
    http.Handle("/metrics", promhttp.Handler())
    http.ListenAndServe(":8080", nil)
}()
http.ListenAndServe(":80", router)

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 2012-10-22
    • 2020-06-30
    • 2014-07-15
    • 2021-11-05
    • 2015-08-31
    • 2012-07-03
    • 2020-06-16
    • 2016-01-21
    相关资源
    最近更新 更多