github.com/GuanceCloud/cliutils@v1.1.21/metrics/http.go (about) 1 // Unless explicitly stated otherwise all files in this repository are licensed 2 // under the MIT License. 3 // This product includes software developed at Guance Cloud (https://www.guance.com/). 4 // Copyright 2021-present Guance, Inc. 5 6 // Package metrics implements datakit's Prometheus metrics 7 8 package metrics 9 10 import ( 11 "net/http" 12 13 "github.com/gin-gonic/gin" 14 "github.com/prometheus/client_golang/prometheus/promhttp" 15 ) 16 17 // MetricServer used to export metrics via HTTP /metrics request. 18 type MetricServer struct { 19 // Metrics request path. 20 URL string `toml:"url" json:"url"` 21 22 // HTTP server address, default to localhost:9090. 23 Listen string `toml:"listen" json:"listen"` 24 25 // Enable or disable the http server. 26 Enable bool `toml:"enable" json:"enable"` 27 28 // Enable or disable Golang related metrics in metrics URL. 29 DisableGoMetrics bool `toml:"disable_go_metrics" json:"disable_go_metrics"` 30 } 31 32 // NewMetricServer create default metric server. 33 func NewMetricServer() *MetricServer { 34 return &MetricServer{ 35 Enable: true, 36 Listen: "localhost:9090", 37 URL: "/metrics", 38 } 39 } 40 41 // Start create HTTP server to serving /metrics request. 42 func (ms *MetricServer) Start() error { 43 if !ms.DisableGoMetrics { 44 MustAddGolangMetrics() 45 } 46 47 if !ms.Enable { 48 return nil 49 } 50 51 http.Handle(ms.URL, promhttp.HandlerFor( 52 reg, 53 promhttp.HandlerOpts{} /*TODO: add options here*/)) 54 return http.ListenAndServe(ms.Listen, nil) 55 } 56 57 // HTTPGinHandler wrap promhttp handler as gin hander. We can 58 // attach url /metrics to a exist gin router like this: 59 // 60 // router := gin.New() 61 // router.GET("/metrics", HTTPGinHandler(promhttp.HandlerOpts{})) 62 func HTTPGinHandler(opt promhttp.HandlerOpts) gin.HandlerFunc { 63 h := promhttp.HandlerFor(reg, opt) 64 return func(c *gin.Context) { 65 h.ServeHTTP(c.Writer, c.Request) 66 } 67 }