Skip to content

Commit

Permalink
move prometheus to its own file
Browse files Browse the repository at this point in the history
  • Loading branch information
poundifdef committed Mar 22, 2024
1 parent 199533d commit 82cb218
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 18 deletions.
25 changes: 25 additions & 0 deletions pkg/api/prometheus.go
@@ -0,0 +1,25 @@
package api

import (
"net/http"
"strconv"
"time"

"github.com/go-chi/chi/middleware"
"github.com/go-chi/chi/v5"
)

func PrometheusMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()

ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(ww, r)

duration := time.Since(start)
routeName := chi.RouteContext(r.Context()).RoutePattern()

latency.WithLabelValues(routeName, strconv.Itoa(ww.Status())).Observe(duration.Seconds())
responseSize.WithLabelValues(routeName).Observe(float64(ww.BytesWritten()))
})
}
18 changes: 0 additions & 18 deletions pkg/api/router.go
Expand Up @@ -3,10 +3,7 @@ package api
import (
"context"
"net/http"
"strconv"
"time"

"github.com/go-chi/chi/middleware"
"github.com/go-chi/chi/v5"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
Expand All @@ -24,21 +21,6 @@ var responseSize = promauto.NewHistogramVec(prometheus.HistogramOpts{
Buckets: prometheus.ExponentialBucketsRange(1000, 100_000_000, 20),
}, []string{"route"})

func PrometheusMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()

ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
next.ServeHTTP(ww, r)

duration := time.Since(start)
routeName := chi.RouteContext(r.Context()).RoutePattern()

latency.WithLabelValues(routeName, strconv.Itoa(ww.Status())).Observe(duration.Seconds())
responseSize.WithLabelValues(routeName).Observe(float64(ww.BytesWritten()))
})
}

type ScratchDataAPI interface {
Select(w http.ResponseWriter, r *http.Request)
Insert(w http.ResponseWriter, r *http.Request)
Expand Down

0 comments on commit 82cb218

Please sign in to comment.