- switch {
- case req.Method != "GET" && req.Method != "HEAD":
- m.next.ServeHTTP(w, req)
- case req.URL.Path == "/metrics.json":
- m.exportJSON(w, req)
- case req.URL.Path == "/metrics":
- m.exportProm.ServeHTTP(w, req)
- default:
- m.next.ServeHTTP(w, req)
- }
+ m.next.ServeHTTP(w, req)
+}
+
+// ServeAPI returns a new http.Handler that serves current data at
+// metrics API endpoints (currently "GET /metrics(.json)?") and passes
+// other requests through to next.
+//
+// If the given token is not empty, that token must be supplied by a
+// client in order to access the metrics endpoints.
+//
+// Typical example:
+//
+// m := Instrument(...)
+// srv := http.Server{Handler: m.ServeAPI("secrettoken", m)}
+func (m *metrics) ServeAPI(token string, next http.Handler) http.Handler {
+ jsonMetrics := auth.RequireLiteralToken(token, http.HandlerFunc(m.exportJSON))
+ plainMetrics := auth.RequireLiteralToken(token, m.exportProm)
+ return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ switch {
+ case req.Method != "GET" && req.Method != "HEAD":
+ next.ServeHTTP(w, req)
+ case req.URL.Path == "/metrics.json":
+ jsonMetrics.ServeHTTP(w, req)
+ case req.URL.Path == "/metrics":
+ plainMetrics.ServeHTTP(w, req)
+ default:
+ next.ServeHTTP(w, req)
+ }
+ })