github.com/wfusion/gofusion@v1.1.14/common/infra/watermill/components/metrics/http.go (about) 1 package metrics 2 3 import ( 4 "net/http" 5 6 "github.com/gin-gonic/gin" 7 "github.com/prometheus/client_golang/prometheus" 8 "github.com/prometheus/client_golang/prometheus/promhttp" 9 ) 10 11 // CreateRegistryAndServeHTTP establishes an HTTP server that exposes the /metrics endpoint for Prometheus at the given address. 12 // It returns a new prometheus registry (to register the metrics on) and a canceling function that ends the server. 13 func CreateRegistryAndServeHTTP(addr string) (registry *prometheus.Registry, cancel func()) { 14 registry = prometheus.NewRegistry() 15 return registry, ServeHTTP(addr, registry) 16 } 17 18 // ServeHTTP establishes an HTTP server that exposes the /metrics endpoint for Prometheus at the given address. 19 // It takes an existing Prometheus registry and returns a canceling function that ends the server. 20 func ServeHTTP(addr string, registry *prometheus.Registry) (cancel func()) { 21 router := gin.New() 22 23 handler := promhttp.HandlerFor(registry, promhttp.HandlerOpts{}) 24 router.GET("/metrics", gin.WrapF(handler.ServeHTTP)) 25 server := http.Server{ 26 Addr: addr, 27 Handler: router, 28 } 29 30 go func() { 31 err := server.ListenAndServe() 32 if err != http.ErrServerClosed { 33 panic(err) 34 } 35 }() 36 37 return func() { _ = server.Close() } 38 }