Skip to content

Commit

Permalink
Merge pull request #118 from nkeonkeo/main
Browse files Browse the repository at this point in the history
Add "web.token" for authentication
  • Loading branch information
czerwonk authored Dec 27, 2024
2 parents 20900dc + c1780ce commit 18e0d39
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ var (
showVersion = kingpin.Flag("version", "Print version information").Default().Bool()
listenAddress = kingpin.Flag("web.listen-address", "Address on which to expose metrics and web interface").Default(":9427").String()
metricsPath = kingpin.Flag("web.telemetry-path", "Path under which to expose metrics").Default("/metrics").String()
metricsToken = kingpin.Flag("web.token", "Token (in http request headers of queries) which to expose metrics").Default("").String()
serverUseTLS = kingpin.Flag("web.tls.enabled", "Enable TLS for web server, default is false").Default().Bool()
serverTlsCertFile = kingpin.Flag("web.tls.cert-file", "The certificate file for the web server").Default("").String()
serverTlsKeyFile = kingpin.Flag("web.tls.key-file", "The key file for the web server").Default("").String()
Expand Down Expand Up @@ -293,7 +294,17 @@ func refreshDNS(tar *targets, monitor *mon.Monitor, cfg *config.Config) {
func startServer(cfg *config.Config, collector *pingCollector) {
var err error
log.Infof("Starting ping exporter (Version: %s)", version)
http.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if *metricsToken != "" {
token := r.URL.Query().Get("token")
if token == "" {
token = r.Header.Get("token")
}
if token != *metricsToken {
w.Write([]byte("wrong token"))
return
}
}
fmt.Fprintf(w, indexHTML, *metricsPath)
})

Expand All @@ -307,7 +318,19 @@ func startServer(cfg *config.Config, collector *pingCollector) {
ErrorLog: l,
ErrorHandling: promhttp.ContinueOnError,
})
http.Handle(*metricsPath, h)
http.HandleFunc(*metricsPath, func(w http.ResponseWriter, r *http.Request) {
if *metricsToken != "" {
token := r.URL.Query().Get("token")
if token == "" {
token = r.Header.Get("token")
}
if token != *metricsToken {
w.Write([]byte("wrong token"))
return
}
}
h.ServeHTTP(w, r)
})

server := http.Server{
Addr: *listenAddress,
Expand Down

0 comments on commit 18e0d39

Please sign in to comment.