Skip to content

Configuration-file example

Load resource policies from a version-controlled YAML or JSON document.

Prerequisites

  • Go 1.24 or newer
  • no external service for the bundled YAML, because it omits redis_url

Run

go run ./examples/configuration_file \
  -config examples/configuration_file/limits.yaml
examples/configuration_file/limits.yaml
gorl:
  strategy: sliding_window
  fail_open: false
  default:
    limit: 100
    window: 1m
  resources:
    login:
      limit: 5
      window: 1m
    search:
      limit: 50
      window: 1s
examples/configuration_file/main.go
// Package main demonstrates loading resource-scoped limits from a YAML or JSON file.
package main

import (
    "context"
    "flag"
    "fmt"
    "log"

    "github.com/AliRizaAynaci/gorl/v2"
    "github.com/AliRizaAynaci/gorl/v2/config"
)

func main() {
    configPath := flag.String("config", "examples/configuration_file/limits.yaml", "path to a GoRL YAML or JSON config")
    flag.Parse()

    cfg, err := config.LoadResourceConfig(*configPath)
    if err != nil {
        log.Fatalf("load config: %v", err)
    }

    limiter, err := gorl.NewResourceLimiter(cfg)
    if err != nil {
        log.Fatalf("create limiter: %v", err)
    }
    defer limiter.Close()

    result, err := limiter.AllowResource(context.Background(), "login", "user-123")
    if err != nil {
        log.Fatalf("evaluate limit: %v", err)
    }

    fmt.Printf("allowed=%v limit=%d remaining=%d\n", result.Allowed, result.Limit, result.Remaining)
}

Expected behavior

The file selects sliding-window behavior and a five-per-minute login policy. The program prints an allowed first decision with four remaining requests.

Production cautions

The loader reads once and does not watch the file. Validate configuration during deployment, protect Redis credentials if a URL is included, and design an explicit limiter replacement lifecycle before attempting live reloads.