Untitled
unknown
golang
a year ago
1.5 kB
6
Indexable
package main
import (
"fmt"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var nomeCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "ping_request_count",
Help: "No of request handled by Ping handler",
},
)
func pong(w http.ResponseWriter, req *http.Request) {
// preprocesso 01, potrebbe dare errore 💣
nome := r.PostFormValue("nome")
if nome == "" {
nomeCounter.With(prometheus.Labels{"status_code": strconv.Itoa(http.StatusBadRequest)}).Inc()
w.WriteHeader(http.StatusBadRequest)
return
}
// preprocesso 02, potrebbe dare errore come sopra
// ...
// potrei avere anche quattro o cinque "step" in cui potrei andare in errore.
// <nome> ha bassa cardinalità , esistono solo 10 possibili nomi pertanto è safe metterlo nei label
//
// Ripeto ogni volta la chiamata a pingCounter.With o c'è un metodo più furbo?
// N.B. racchiudere il tutto in un middleware non penso sia fattibile in quanto dovrei portarmi dietro <nome> noto solo
// dopo delle validazioni svolte proprio da questo handler
// se arrivo qua è tutto OK 🚀
nomeCounter.With(prometheus.Labels{"status_code": strconv.Itoa(http.StatusOK), "nome": nome}).Inc()
fmt.Fprintf(w, "pong")
}
func main() {
prometheus.MustRegister(pingCounter)
http.HandleFunc("/ping", ping)
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8090", nil)
}Editor is loading...
Leave a Comment