package main
import (
"fmt"
"log"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// 定义一个指标,用于记录请求总数
var requestTotal = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "request_total",
Help: "Total number of requests",
},
)
// 初始化函数,注册指标
func init() {
prometheus.MustRegister(requestTotal)
}
// 处理请求的函数,每次请求都会增加指标的值
func handler(w http.ResponseWriter, r *http.Request) {
requestTotal.Inc()
fmt.Fprintf(w, "Hello, world!")
}
func main() {
// 设置路由,使用promhttp包提供的Handler函数
http.HandleFunc("/", handler)
http.Handle("/metrics", promhttp.Handler())
// 监听8080端口
addr := "0.0.0.0:8080"
fmt.Printf("Listening on %s\n", addr)
log.Fatal(http.ListenAndServe(addr, nil))
}
标签:文件,exporter,http,addr,promhttp,示例,fmt,prometheus,func
From: https://www.cnblogs.com/wanghongwei-dev/p/17527939.html