Untitled
user_4655978
golang
a year ago
1.9 kB
11
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: "nome_request_count",
Help: "No of request handled by nome handler",
},
)
func getCognome(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
// il nome è stato deserializzato correttamente, chiamo la mia business logic
cognome, err := db.GetCognome(nome)
if err != nil {
nomeCounter.With(prometheus.Labels{"status_code": strconv.Itoa(http.StatusBadRequest), "nome": nome}).Inc()
w.WriteHeader(http.StatusInternalServerError)
return
}
// se arrivo qua è tutto OK 🚀
nomeCounter.With(prometheus.Labels{"status_code": strconv.Itoa(http.StatusOK), "nome": nome}).Inc()
fmt.Fprintf(w, cognome)
}
func main() {
prometheus.MustRegister(pingCounter)
http.HandleFunc("/nome", getCognome)
http.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8090", nil)
}Editor is loading...
Leave a Comment