woj-server/internal/web/metrics/middleware.go

44 lines
921 B
Go
Raw Normal View History

2022-09-07 23:34:37 +08:00
package metrics
import (
2023-07-14 21:47:11 +08:00
"git.0x7f.app/WOJ/woj-server/internal/e"
"git.0x7f.app/WOJ/woj-server/pkg/utils"
2022-09-07 23:34:37 +08:00
"github.com/gin-gonic/gin"
"net/http"
"strings"
"time"
)
2023-07-15 16:19:49 +08:00
func (s *service) SetLogPaths(paths []string) {
s.logPaths = paths
2022-09-07 23:34:37 +08:00
}
2023-07-15 16:19:49 +08:00
func (s *service) Handler() gin.HandlerFunc {
2022-09-07 23:34:37 +08:00
return func(c *gin.Context) {
url := c.Request.URL.String()
method := c.Request.Method
2023-07-15 16:19:49 +08:00
if !utils.Contains(s.logPaths, func(path string) bool { return strings.HasPrefix(url, path) }) {
2022-09-07 23:34:37 +08:00
c.Next()
return
}
start := time.Now()
c.Next()
elapsed := float64(time.Since(start)) / float64(time.Millisecond)
status := c.Writer.Status()
success := !c.IsAborted() && (status == http.StatusOK)
errCode, _ := c.Get("err")
2022-09-20 14:15:21 +08:00
err, ok := errCode.(e.Status)
2022-09-07 23:34:37 +08:00
if !ok {
success = false
2022-09-17 09:23:36 +08:00
err = e.Unknown
} else if err != e.Success {
success = false
2022-09-07 23:34:37 +08:00
}
2023-07-15 16:19:49 +08:00
s.Record(method, url, success, status, err, elapsed)
2022-09-07 23:34:37 +08:00
}
}