package main
import (
"fmt"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
"time"
)
var (
// Create a new instance of a gauge metric.
waf_mgt_server_exception = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "waf_mgt_server_exception",
Help: "waf mgt server exception",
}, []string{"name"})
)
type basicAuthHandler struct {
handler http.HandlerFunc
user string
password string
}
func (h *basicAuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
user, password, ok := r.BasicAuth()
if !ok || password != h.password || user != h.user {
w.Header().Set("WWW-Authenticate", "Basic realm=\"metrics\"")
http.Error(w, "Invalid username or password", http.StatusUnauthorized)
return
}
h.handler(w, r)
return
}
func startMetricServer() {
srv := &http.Server{Addr: ":8080"}
handler := &basicAuthHandler{
handler: promhttp.Handler().ServeHTTP,
user: "waf",
password: "waf",
}
http.Handle("/metrics", handler)
http.HandleFunc("/ready", func(writer http.ResponseWriter, request *http.Request) {
_, _ = writer.Write([]byte("ok"))
})
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
// unexpected error. port in use?
fmt.Printf("metric server ListenAndServe(): %v\n", err)
}
}
func updateMetric() {
// curl service status here...
name := "mgt-api"
status := float64(0)
waf_mgt_server_exception.With(prometheus.Labels{
"name": name,
}).Set(status)
}
func main() {
// Register the metric with Prometheus's default registry.
prometheus.MustRegister(waf_mgt_server_exception)
// Start a new goroutine to update the metric every minute.
go func() {
for {
select {
case <-time.After(time.Minute):
// Update the gauge metric with some value.
// This is where you would put the logic to obtain a real value.
updateMetric()
}
}
}()
// Start an HTTP server that Prometheus can scrape for metrics.
startMetricServer()
}
go程序编写云原生metrics接口
最新推荐文章于 2025-07-12 21:23:33 发布