Examples - Go Rules Engine
This folder contains usage examples of the Go rules engine.
π Available Examples
1. basic/main.go
Basic Example - Simple age verification with a single rule.
go run examples/basic/main.go
Demonstrates:
- β
Engine creation
- β
Simple rule with condition
- β
greater_than operator
- β
Tests with different values
2. json/main.go
JSON Loading - Load rules and facts from JSON.
go run examples/json/main.go
Demonstrates:
- β
Unmarshaling JSON rules
- β
Unmarshaling JSON facts
- β
Adding rules to engine
- β
Adding facts to almanac
- β
VIP and regular rules
3. custom-operator/main.go
Custom Operators - Creating custom operators.
go run examples/custom-operator/main.go
Demonstrates:
- β
Operator interface
- β
CustomOperator implementation
- β
starts_with, ends_with, between operators
- β
RegisterOperator to register operators
4. advanced/main.go
Advanced Features - Callbacks, handlers and dynamic facts.
go run examples/advanced/main.go
Demonstrates:
- β
Named callbacks with
RegisterCallback
- β
Global handler
OnSuccess
- β
Specific handler per event type
On()
- β
Dynamic facts (discount calculation)
- β
Multiple simultaneous handlers
5. full-demo.go
Complete Demonstration - All features in a single example.
go run examples/full-demo.go
Demonstrates:
- β
Simple and complex rules
- β
Nested conditions (all/any)
- β
Callbacks and handlers
- β
JSON loading
- β
Dynamic facts
- β
JSONPath
- β
Event history
π Execution
From the project root:
# Basic example
go run examples/basic/main.go
# JSON
go run examples/json/main.go
# Custom operators
go run examples/custom-operator/main.go
# Advanced
go run examples/advanced/main.go
# Full demo
go run examples/full-demo.go
π Complete Documentation
See the main README for complete API documentation.
π‘ Quick Start
To create your own application:
-
Import:
import gorulesengine "github.com/deadelus/go-rules-engine/src"
-
Engine:
engine := gorulesengine.NewEngine()
-
Rule:
rule := &gorulesengine.Rule{
Name: "my-rule",
Priority: 100,
Conditions: gorulesengine.ConditionSet{
All: []gorulesengine.ConditionNode{
{
Condition: &gorulesengine.Condition{
Fact: "age",
Operator: "greater_than",
Value: 18,
},
},
},
},
Event: gorulesengine.Event{
Type: "adult",
},
}
engine.AddRule(rule)
-
Almanac:
almanac := gorulesengine.NewAlmanac([]*gorulesengine.Fact{})
almanac.AddFact("age", 25)
-
Run:
results, err := engine.Run(almanac)
if err != nil {
log.Fatal(err)
}
for _, result := range results {
if result.Result {
fmt.Printf("β
%s\n", result.Event.Type)
}
}
π Example Structure
examples/
βββ README.md # This file
βββ full-demo.go # Complete demo
βββ basic/ # Basic example
β βββ main.go
βββ json/ # JSON loading
β βββ main.go
βββ custom-operator/ # Custom operators
β βββ main.go
βββ advanced/ # Advanced features
βββ main.go
Check each example for specific use cases!