ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 原生实现 速出自定义的 metrics 格式 ``` package main import ( "fmt" "log" "math/rand" "net/http" "sync" "time" ) // 定义指标结构体 type Metrics struct { mu sync.Mutex roomTemperature float64 totalRequests int } // 全局指标实例 var metrics = &Metrics{} // 生成随机温度并更新指标 func updateMetrics() { for { metrics.mu.Lock() metrics.roomTemperature = 15.0 + rand.Float64()*(25.0-15.0) metrics.totalRequests++ metrics.mu.Unlock() time.Sleep(1 * time.Second) } } // 处理 /metrics 路径的请求 func metricsHandler(w http.ResponseWriter, r *http.Request) { metrics.mu.Lock() defer metrics.mu.Unlock() // 设置响应头为 text/plain w.Header().Set("Content-Type", "text/plain; version=0.0.4") // 格式化并写入指标 fmt.Fprintf(w, "# HELP room_temperature_celsius Temperature of the room in Celsius\n") fmt.Fprintf(w, "# TYPE room_temperature_celsius gauge\n") fmt.Fprintf(w, "room_temperature_celsius %f\n", metrics.roomTemperature) fmt.Fprintf(w, "# HELP total_requests Total number of requests handled\n") fmt.Fprintf(w, "# TYPE total_requests counter\n") fmt.Fprintf(w, "total_requests %d\n", metrics.totalRequests) } func main() { // 启动指标更新协程 go updateMetrics() // 设置 HTTP 路由 http.HandleFunc("/metrics", metricsHandler) // 启动 HTTP 服务器 addr := ":8080" fmt.Printf("Prometheus Exporter is running on http://localhost%s/metrics\n", addr) log.Fatal(http.ListenAndServe(addr, nil)) } ```