-
Notifications
You must be signed in to change notification settings - Fork 1
/
metrics.go
66 lines (57 loc) · 1.55 KB
/
metrics.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package xmetrics
import (
"github.com/admpub/nging/v5/application/library/config"
"github.com/admpub/nging/v5/application/library/config/extend"
"github.com/webx-top/com"
"github.com/webx-top/echo"
echoPrometheus "github.com/webx-top/echo-prometheus"
"github.com/webx-top/echo/middleware"
)
var (
_ extend.Reloader = &Metrics{}
)
func New() *Metrics {
return &Metrics{
BasicAuth: &BasicAuth{},
}
}
type Metrics struct {
*BasicAuth
Enable bool `json:"enable"`
}
func (m *Metrics) Reload() error {
return nil
}
type BasicAuth struct {
User string `json:"user"`
Password string `json:"password"`
}
func RequestMiddleware() echo.Middleware {
prometheusConfig := echoPrometheus.DefaultConfig
prometheusConfig.Skipper = RequestSkipper()
prometheusConfig.OnlyRoutePath = true
return echoPrometheus.MetricsMiddlewareWithConfig(prometheusConfig)
}
func RequestSkipper() echo.Skipper {
return func(c echo.Context) bool {
mc, ok := config.FromFile().Extend.Get(Name).(*Metrics)
if !ok || !mc.Enable {
return true
}
return c.Request().URL().Path() == `/metrics`
}
}
func ResponseMiddleware() echo.Middleware {
return middleware.BasicAuth(func(user string, password string) bool {
mc, ok := config.FromFile().Extend.Get(Name).(*Metrics)
if !ok || mc.BasicAuth == nil {
return false
}
if !mc.Enable || len(mc.User) == 0 || len(mc.Password) == 0 {
return false
}
return mc.User == user && mc.Password == password
}, func(c echo.Context) bool {
return com.IsLocalhost(c.Domain()) && com.IsLocalhost(c.Request().RemoteAddress())
})
}