metrics: Add http_requests metric
This commit is contained in:
33
router.go
33
router.go
@@ -5,6 +5,7 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"gitea.hashru.nl/dsprenkels/rushlink/internal/db"
|
||||
@@ -37,6 +38,37 @@ func recoveryMiddleware(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
type statusResponseWriter struct {
|
||||
Inner http.ResponseWriter
|
||||
StatusCode int
|
||||
}
|
||||
|
||||
func (w *statusResponseWriter) Header() http.Header {
|
||||
return w.Inner.Header()
|
||||
}
|
||||
|
||||
func (w *statusResponseWriter) Write(buf []byte) (int, error) {
|
||||
if w.StatusCode == 0 {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
return w.Inner.Write(buf)
|
||||
}
|
||||
|
||||
func (w *statusResponseWriter) WriteHeader(statusCode int) {
|
||||
w.StatusCode = statusCode
|
||||
w.Inner.WriteHeader(statusCode)
|
||||
}
|
||||
|
||||
func metricsMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
srw := statusResponseWriter{Inner: w}
|
||||
next.ServeHTTP(&srw, r)
|
||||
status := strconv.Itoa(srw.StatusCode)
|
||||
metricRequestsTotalCounter.WithLabelValues(status, r.Method).Inc()
|
||||
})
|
||||
}
|
||||
|
||||
// StartMainServer starts the main http server listening on addr.
|
||||
func StartMainServer(addr string, db *db.Database, fs *db.FileStore) {
|
||||
rl := rushlink{
|
||||
db: db,
|
||||
@@ -46,6 +78,7 @@ func StartMainServer(addr string, db *db.Database, fs *db.FileStore) {
|
||||
// Initialize Gorilla router
|
||||
router := mux.NewRouter()
|
||||
router.Use(recoveryMiddleware)
|
||||
router.Use(metricsMiddleware)
|
||||
router.HandleFunc("/", rl.indexGetHandler).Methods("GET")
|
||||
router.HandleFunc("/", rl.newPasteHandler).Methods("POST")
|
||||
router.HandleFunc("/{key:[A-Za-z0-9-_]{4,}}", rl.viewPasteHandler).Methods("GET")
|
||||
|
||||
Reference in New Issue
Block a user