Skip to content

Prometheus metrics

Expose allow, deny, and limiter-latency metrics beside a protected endpoint.

Prerequisites

  • Go 1.24 or newer
  • port 8080 available

Run

go run ./examples/prometheus
examples/prometheus/main.go
// Package main demonstrates exporting GoRL metrics with Prometheus.
package main

import (
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/AliRizaAynaci/gorl/v2"
    "github.com/AliRizaAynaci/gorl/v2/core"
    "github.com/AliRizaAynaci/gorl/v2/metrics"
    mw "github.com/AliRizaAynaci/gorl/v2/middleware/http"
    "github.com/prometheus/client_golang/prometheus/promhttp"
)

func main() {
    collector := metrics.NewPrometheusCollector("gorl", "example")
    metrics.RegisterPrometheusCollectors(collector)

    limiter, err := gorl.New(core.Config{
        Strategy: core.SlidingWindow,
        Limit:    5,
        Window:   time.Minute,
        Metrics:  collector,
    })
    if err != nil {
        log.Fatal(err)
    }
    defer limiter.Close()

    mux := http.NewServeMux()
    mux.Handle("/metrics", promhttp.Handler())
    mux.Handle("/api/", mw.RateLimit(limiter, mw.Options{
        KeyFunc: mw.KeyByIP(),
    }, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
        fmt.Fprintln(w, "allowed")
    })))

    log.Println("API: http://localhost:8080/api/")
    log.Println("metrics: http://localhost:8080/metrics")
    log.Fatal(http.ListenAndServe(":8080", mux))
}

Generate decisions, then inspect metrics:

curl http://localhost:8080/api/
curl http://localhost:8080/metrics | grep '^gorl_example_'

Expected behavior

Requests to /api/ update:

gorl_example_allow_total
gorl_example_deny_total
gorl_example_request_duration_seconds

The /metrics endpoint itself is not protected in this example.

Production cautions

Register each collector name once; the helper uses the default registry and panics on duplicate registration. Restrict metrics endpoint access at the network or application layer. Monitor Redis separately because the built-in collector does not expose backend availability or error counters.