diff --git a/http/http.go b/http/http.go index dae37ca..33f230a 100644 --- a/http/http.go +++ b/http/http.go @@ -100,7 +100,7 @@ func newResponseWriterWithMetrics(w http.ResponseWriter) *responseWriterWithMetr return &responseWriterWithMetrics{ ResponseWriter: w, responseWriterMetrics: responseWriterMetrics{ - statusCode: -1, + statusCode: 200, resSize: 0, }, } @@ -173,10 +173,6 @@ func StdMetricsMiddleware(next http.Handler) http.Handler { next.ServeHTTP(wrappedRes, req) reqDur := float64(time.Since(start)) / float64(time.Second) - if metrics.statusCode == -1 { - return - } - statusCode := strconv.Itoa(metrics.statusCode) reqSizeHistogramVec.WithLabelValues(statusCode, method, path).Observe(reqSz) diff --git a/http/prometheus.go b/http/prometheus.go index c033b92..740be47 100644 --- a/http/prometheus.go +++ b/http/prometheus.go @@ -2,10 +2,9 @@ package isuhttp import ( "net/http" - "strconv" - "strings" + "regexp" + "sync" - "github.com/google/uuid" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" "github.com/valyala/fasthttp" @@ -102,38 +101,40 @@ func fastHTTPReqSize(req *fasthttp.Request) float64 { return size } -type replacePair struct { - old, new string -} +var ( + filterCacheLocker = &sync.RWMutex{} + filterCache = make(map[string]string, 50) + filterReList = []struct { + re *regexp.Regexp + to string + }{{ + // uuid + re: regexp.MustCompile(`[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}`), + to: "", + }, { + // number + re: regexp.MustCompile(`\d+`), + to: "", + }} +) var FilterFunc = func(path string) string { - pathList := strings.Split(path, "/") - - replacePairs := []replacePair{} - for _, v := range pathList { - _, err := uuid.Parse(v) - if err == nil { - replacePairs = append(replacePairs, replacePair{ - old: v, - new: "", - }) - - continue - } + newPath, ok := func() (string, bool) { + filterCacheLocker.RLock() + defer filterCacheLocker.RUnlock() - _, err = strconv.Atoi(v) - if err == nil { - replacePairs = append(replacePairs, replacePair{ - old: v, - new: "", - }) - - continue + if v, ok := filterCache[path]; ok { + return v, true } + + return "", false + }() + if ok { + return newPath } - for _, pair := range replacePairs { - path = strings.Replace(path, pair.old, pair.new, 1) + for _, re := range filterReList { + path = re.re.ReplaceAllString(path, re.to) } return path