add auther for metrics
This commit is contained in:
@ -4,6 +4,7 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-gost/core/auth"
|
||||
"github.com/go-gost/core/service"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
)
|
||||
@ -13,7 +14,8 @@ const (
|
||||
)
|
||||
|
||||
type options struct {
|
||||
path string
|
||||
path string
|
||||
auther auth.Authenticator
|
||||
}
|
||||
|
||||
type Option func(*options)
|
||||
@ -24,6 +26,12 @@ func PathOption(path string) Option {
|
||||
}
|
||||
}
|
||||
|
||||
func AutherOption(auther auth.Authenticator) Option {
|
||||
return func(o *options) {
|
||||
o.auther = auther
|
||||
}
|
||||
}
|
||||
|
||||
type metricService struct {
|
||||
s *http.Server
|
||||
ln net.Listener
|
||||
@ -44,7 +52,16 @@ func NewService(addr string, opts ...Option) (service.Service, error) {
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle(options.path, promhttp.Handler())
|
||||
mux.Handle(options.path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if options.auther != nil {
|
||||
u, p, _ := r.BasicAuth()
|
||||
if _, ok := options.auther.Authenticate(r.Context(), u, p); !ok {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
}
|
||||
promhttp.Handler().ServeHTTP(w, r)
|
||||
}))
|
||||
return &metricService{
|
||||
s: &http.Server{
|
||||
Handler: mux,
|
||||
|
Reference in New Issue
Block a user