go程序编写云原生metrics接口

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()
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值