Skip to content
Snippets Groups Projects
prometheus_middleware.go 702 B
Newer Older
package orusapi

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/prometheus/client_golang/prometheus/promhttp"
)

// Prometheus serves the '/metrics' endpoint.
func Prometheus(path string) func(next http.Handler) http.Handler {
	handler := promhttp.Handler()

	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
			if strings.HasPrefix(r.URL.Path, path) {
				handler.ServeHTTP(rw, r)
Axel Prel's avatar
Axel Prel committed

				return
			}

			if next == nil {
				rw.Header().Set("Content-Type", "text/plain")
				rw.WriteHeader(http.StatusNotFound)
				_, _ = rw.Write([]byte(fmt.Sprintf("%q not found", path)))
Axel Prel's avatar
Axel Prel committed