Documentation
¶
Overview ¶
Package evaluator provides a simple expression language for querying Go structs. Expressions are represented as Go structs which can be evaluated against arbitrary values or composed together using logical operators. The package also supports marshaling and unmarshaling expressions to and from JSON for storage or transmission.
Example (SimpleParser) ¶
Example_simpleParser demonstrates parsing a string query.
package main
import (
"fmt"
"log"
"github.com/arran4/go-evaluator/parser/simple"
)
func main() {
queryString := `Category is "Electronics" and Price < 1000`
query, err := simple.Parse(queryString)
if err != nil {
log.Fatal(err)
}
type Product struct {
Name string
Category string
Price float64
}
result, err := query.Evaluate(&Product{
Name: "Laptop",
Category: "Electronics",
Price: 999.99,
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
Output: true
Index ¶
- func Compare(a, b interface{}) (int, error)
- func IsTruthy(v interface{}) (bool, error)
- type AndExpression
- type BoolType
- type Comparator
- type ComparisonExpression
- type Constant
- type ContainsExpression
- type Context
- type Expression
- type Field
- type Function
- type FunctionExpression
- type Getter
- type GreaterThanExpression
- type GreaterThanOrEqualExpression
- type IContainsExpression
- type If
- type IsExpression
- type IsNotExpression
- type LessThanExpression
- type LessThanOrEqualExpression
- type NotExpression
- type OrExpression
- type Query
- type QueryRaw
- type Self
- type Term
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type AndExpression ¶
type AndExpression struct {
Expressions []Query `json:"Expressions"`
}
AndExpression evaluates to true only if all child Expressions do as well.
type BoolType ¶ added in v0.0.2
type BoolType struct {
Term Term
}
BoolType converts the term result to a boolean.
type Comparator ¶ added in v0.0.2
Comparator allows for custom comparison logic.
type ComparisonExpression ¶ added in v0.0.2
type ComparisonExpression struct {
LHS Term
RHS Term
Operation string // eq, neq, gt, gte, lt, lte, contains, icontains
}
ComparisonExpression evaluates a comparison between two Terms.
type Constant ¶ added in v0.0.2
type Constant struct {
Value interface{}
}
Constant represents a constant value term.
type ContainsExpression ¶
type ContainsExpression struct {
Field string
Value interface{}
}
ContainsExpression checks whether a slice field contains the given Value, or if a string field contains the given substring.
type Context ¶ added in v0.0.2
Context holds execution context for the evaluator, including variables and functions.
func GetContext ¶ added in v0.0.2
GetContext extracts the Context from the variadic options, or returns a default one.
type Expression ¶
type Expression interface {
// Evaluate returns true if the expression matches the supplied value.
Evaluate(i interface{}, opts ...any) (bool, error)
}
Expression represents a single boolean expression that can be evaluated against a struct value.
type Field ¶ added in v0.0.2
type Field struct {
Name string
}
Field represents a field lookup term.
type Function ¶ added in v0.0.2
type Function interface {
Call(args ...interface{}) (interface{}, error)
}
Function defines the interface for a function that can be called by FunctionExpression.
type FunctionExpression ¶ added in v0.0.2
FunctionExpression represents a function call.
func (FunctionExpression) Evaluate ¶ added in v0.0.2
func (f FunctionExpression) Evaluate(i interface{}, opts ...any) (interface{}, error)
Example ¶
ExampleFunctionExpression_Evaluate demonstrates how to use the FunctionExpression to execute custom logic within the evaluator.
// 1. Define a custom function
// This function sums all numeric arguments
sumFunc := &SumFunction{}
// 2. Build the expression tree
// We want to calculate: Sum(10, 20)
expr := evaluator.FunctionExpression{
Func: sumFunc,
Args: []evaluator.Term{
evaluator.Constant{Value: 10},
evaluator.Constant{Value: 20},
},
}
// 3. Evaluate the expression
result, err := expr.Evaluate(nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Sum: %v\n", result)
// 4. Nested usage
// Calculate: Sum(Sum(5, 5), 10) -> Sum(10, 10) -> 20
nestedExpr := evaluator.FunctionExpression{
Func: sumFunc,
Args: []evaluator.Term{
evaluator.FunctionExpression{
Func: sumFunc,
Args: []evaluator.Term{
evaluator.Constant{Value: 5},
evaluator.Constant{Value: 5},
},
},
evaluator.Constant{Value: 10},
},
}
resultNested, err := nestedExpr.Evaluate(nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Nested Sum: %v\n", resultNested)
Output: Sum: 30 Nested Sum: 20
type GreaterThanExpression ¶
type GreaterThanExpression struct {
Field string
Value interface{}
// contains filtered or unexported fields
}
GreaterThanExpression compares Field to Value and succeeds when the field is greater than the provided value.
type GreaterThanOrEqualExpression ¶
type GreaterThanOrEqualExpression struct {
Field string
Value interface{}
// contains filtered or unexported fields
}
GreaterThanOrEqualExpression succeeds when Field is greater than or equal to Value.
type IContainsExpression ¶ added in v0.0.2
type IContainsExpression struct {
Field string
Value interface{}
}
IContainsExpression checks whether a string field contains the given substring (case-insensitive).
type IsExpression ¶
type IsExpression struct {
Field string
Value interface{}
}
IsExpression succeeds when the specified Field equals Value.
type IsNotExpression ¶
type IsNotExpression struct {
Field string
Value interface{}
}
IsNotExpression succeeds when the specified Field does not equal Value.
type LessThanExpression ¶
type LessThanExpression struct {
Field string
Value interface{}
// contains filtered or unexported fields
}
LessThanExpression succeeds when Field is strictly less than Value.
type LessThanOrEqualExpression ¶
type LessThanOrEqualExpression struct {
Field string
Value interface{}
// contains filtered or unexported fields
}
LessThanOrEqualExpression succeeds when Field is less than or equal to Value.
type NotExpression ¶
type NotExpression struct {
Expression Query `json:"Expression"`
}
NotExpression inverts the result of a single child Expression.
type OrExpression ¶
type OrExpression struct {
Expressions []Query `json:"Expressions"`
}
OrExpression evaluates to true if any of the child Expressions do.
type Query ¶
type Query QueryRaw
Query wraps QueryRaw and provides evaluation and JSON unmarshalling helpers.
Example (UnmarshalJSON) ¶
ExampleQuery_unmarshalJSON shows how to unmarshal a query from JSON.
js := `{
"Expression": {
"Type": "Contains",
"Expression": {
"Field": "Tags",
"Value": "go"
}
}
}`
var q evaluator.Query
_ = json.Unmarshal([]byte(js), &q)
type Post struct{ Tags []string }
v, err := q.Evaluate(&Post{Tags: []string{"go", "news"}})
if err != nil {
log.Fatal(err)
}
fmt.Println(v)
Output: true
func (*Query) Evaluate ¶
Example ¶
ExampleQuery_Evaluate demonstrates manual construction of a query and evaluation.
q := evaluator.Query{
Expression: &evaluator.AndExpression{Expressions: []evaluator.Query{
{Expression: &evaluator.IsExpression{Field: "Name", Value: "bob"}},
{Expression: &evaluator.GreaterThanExpression{Field: "Age", Value: 30}},
}},
}
type User struct {
Name string
Age int
}
v, err := q.Evaluate(&User{Name: "bob", Age: 35})
if err != nil {
log.Fatal(err)
}
fmt.Println(v)
Output: true
func (Query) MarshalJSON ¶
func (*Query) UnmarshalJSON ¶
type QueryRaw ¶
type QueryRaw struct {
Expression Expression `json:"-"`
ExpressionRawJson json.RawMessage `json:"Expression"`
}
QueryRaw is the JSON representation of a query. ExpressionRawJson stores the raw JSON for the underlying expression and is resolved during unmarshalling.