feat(exporter): add prometheus exporter for cache, database & webserver stats
This commit is contained in:
parent
95a3a16fdc
commit
4bbda96dc7
8 changed files with 405 additions and 18 deletions
68
internal/exporter/middleware.go
Normal file
68
internal/exporter/middleware.go
Normal file
|
@ -0,0 +1,68 @@
|
|||
package exporter
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
)
|
||||
|
||||
type RequestData struct {
|
||||
Latency time.Duration
|
||||
Request *http.Request
|
||||
Start time.Time
|
||||
}
|
||||
|
||||
type RequestDataQueue struct {
|
||||
mu sync.Mutex
|
||||
data []RequestData
|
||||
}
|
||||
|
||||
func NewRequestDataQueue() *RequestDataQueue {
|
||||
return &RequestDataQueue{
|
||||
data: []RequestData{},
|
||||
}
|
||||
}
|
||||
|
||||
func (q *RequestDataQueue) Add(data RequestData) {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
q.data = append(q.data, data)
|
||||
}
|
||||
|
||||
func (q *RequestDataQueue) ConsumeAll() []RequestData {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
data := q.data
|
||||
q.data = nil
|
||||
return data
|
||||
}
|
||||
|
||||
type Middleware struct {
|
||||
queue *RequestDataQueue
|
||||
}
|
||||
|
||||
func NewMiddleware(queue *RequestDataQueue) func(next http.Handler) http.Handler {
|
||||
m := Middleware{
|
||||
queue: queue,
|
||||
}
|
||||
return m.handler
|
||||
}
|
||||
|
||||
func (m Middleware) handler(next http.Handler) http.Handler {
|
||||
fn := func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
next.ServeHTTP(ww, r)
|
||||
|
||||
m.queue.Add(
|
||||
RequestData{
|
||||
Latency: time.Since(start),
|
||||
Request: r,
|
||||
Start: start,
|
||||
},
|
||||
)
|
||||
}
|
||||
return http.HandlerFunc(fn)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue