examples

package
v0.33.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: Apache-2.0, BSD-3-Clause Imports: 0 Imported by: 0

README

CEL-Go Examples

This directory contains executable Go examples showcasing the CEL-Go APIs and language features. All examples correspond to topics on CEL by Example and are implemented as Go Example...() functions runnable via go test and viewable via godoc.


1. Quickstart & Compilation (cel.Compile)

Compile and evaluate expressions using cel.Compile():

package main

import (
	"fmt"
	"log"

	"cel.dev/cel-go/cel"
)

func main() {
	prg, err := cel.Compile(`"Hello world! I'm " + name + "."`,
		cel.Variable("name", cel.StringType),
	)
	if err != nil {
		log.Fatalln(err)
	}
	out, _, err := prg.Eval(map[string]any{
		"name": "CEL",
	})
	if err != nil {
		log.Fatalln(err)
	}
	fmt.Println(out)
	// Output: Hello world! I'm CEL.
}

For custom options and extensions:

prg, err := cel.Compile(`"%s! I'm %s.".format([greeting, name])`,
	ext.Strings(),
	cel.Variable("greeting", cel.StringType),
	cel.Variable("name", cel.StringType),
)
out, _, err := prg.Eval(map[string]any{
	"greeting": "Hello world",
	"name":     "CEL",
})

Source code: example_cel_compile_test.go | Source code: example_cel_context_eval_test.go


2. Strings & Numbers

Covers string functions (endsWith, contains, startsWith, matches, size), string concatenation (+), numeric comparisons, and ext.Strings() extensions:

prg, _ := cel.Compile(`"hello world".replace("world", "CEL")`, ext.Strings())
out, _, _ := prg.Eval(cel.NoVars())
fmt.Println(out) // hello CEL

Source code: example_cel_strings_and_numbers_test.go


3. Collections (Lists & Maps)

Membership (in), size (size()), indexing ([0]), quantifier macros (exists(), all()), and filtering (filter()):

prg, _ := cel.Compile(`tags.exists(t, t.startsWith("ex"))`, cel.Variable("tags", cel.DynType))
out, _, _ := prg.Eval(map[string]any{
	"tags": []string{"express", "gift-wrapped"},
})
fmt.Println(out) // true

Source code: example_cel_collections_test.go


4. Timestamps & Durations

Time component extraction (getFullYear(), getHours()), timezones, timestamp arithmetic, and epoch conversions:

prg, _ := cel.Compile(`timestamp("2024-01-15T10:30:45Z") + duration("1h")`)
out, _, _ := prg.Eval(cel.NoVars())
fmt.Println(out) // 2024-01-15 11:30:45 +0000 UTC

Source code: example_cel_time_test.go


5. Logic & Conditions

Logical operators (!, &&, ||), short-circuiting, and conditional (ternary) operators:

prg, _ := cel.Compile(`age >= 18 ? "adult" : "minor"`, cel.Variable("age", cel.IntType))
out, _, _ := prg.Eval(map[string]any{"age": 20})
fmt.Println(out) // adult

Source code: example_cel_logic_and_conditions_test.go


6. Transforming Data

Building maps, list transformation with map(), and filtering before transformation:

prg, _ := cel.Compile(`nums.map(x, x % 2 == 0, x * 10)`, cel.Variable("nums", cel.ListType(cel.IntType)))
out, _, _ := prg.Eval(map[string]any{
	"nums": []int64{1, 2, 3, 4, 5},
})
fmt.Println(out) // [20, 40]

Source code: example_cel_transforming_data_test.go


7. Type Conversions & Introspection

Type casting (int(), uint(), double(), string(), bytes(), dyn()) and type inspection (type(x)):

prg, _ := cel.Compile(`type(42) == int`)
out, _, _ := prg.Eval(cel.NoVars())
fmt.Println(out) // true

Source code: example_cel_type_conversions_test.go


8. Protocol Buffers & Well-Known Types

Protobuf message construction, enums, field presence has(), default values, wrappers (StringValue, BoolValue), and google.protobuf.Struct:

prg, _ := cel.Compile(`has(user.single_string)`,
	cel.Types(&proto3pb.TestAllTypes{}),
	cel.Variable("user", cel.ObjectType("google.expr.proto3.test.TestAllTypes")),
)
out, _, _ := prg.Eval(map[string]any{
	"user": &proto3pb.TestAllTypes{SingleString: "Alice"},
})
fmt.Println(out) // true

Source code: example_cel_protocol_buffers_test.go


9. Operators

Arithmetic, ordering, equality, and null handling:

prg, _ := cel.Compile(`(2 + 3) * 4`)
out, _, _ := prg.Eval(cel.NoVars())
fmt.Println(out) // 20

Source code: example_cel_operators_test.go


10. Custom Functions

Extend CEL with global functions (cel.Overload) or member functions (cel.MemberOverload):

prg, _ := cel.Compile(`shake_hands(i, you)`,
	cel.Variable("i", cel.StringType),
	cel.Variable("you", cel.StringType),
	cel.Function("shake_hands",
		cel.Overload("shake_hands_string_string",
			[]*cel.Type{cel.StringType, cel.StringType},
			cel.StringType,
			cel.BinaryBinding(func(lhs, rhs ref.Val) ref.Val {
				return types.String(fmt.Sprintf("%s and %s are shaking hands.", lhs, rhs))
			}),
		),
	),
)
out, _, _ := prg.Eval(map[string]any{"i": "CEL", "you": "world"})
fmt.Println(out) // CEL and world are shaking hands.

Source code: example_cel_custom_functions_test.go


11. Custom Macros

Define AST transformation macros using parser.NewGlobalMacro or parser.NewReceiverMacro:

joinMacro := parser.NewGlobalMacro("join_str", 2, func(eh parser.ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) {
    space := eh.NewLiteral(types.String(" "))
    first := eh.NewCall(operators.Add, args[0], space)
    return eh.NewCall(operators.Add, first, args[1]), nil
})
prg, _ := cel.Compile(`join_str("Hello", "World")`, cel.Macros(joinMacro))
out, _, _ := prg.Eval(cel.NoVars())
fmt.Println(out) // Hello World

Source code: example_cel_custom_macros_test.go


12. Execution Cost Analysis

Static cost estimation with env.EstimateCost() and dynamic limit enforcement with cel.CostTracking() & cel.CostLimit():

env, _ := cel.NewEnv(cel.Variable("items", cel.ListType(cel.IntType)))
ast, _ := env.Compile(`items.map(x, x * x).size()`)
cost, _ := env.EstimateCost(ast, costEstimator{hints: map[string]uint64{"items": 5, "items.@items": 10}})
prg, _ := env.Program(ast, cel.CostTracking(runtimeEstimator{}), cel.CostLimit(1000))
out, details, _ := prg.Eval(map[string]any{"items": []int64{1, 2, 3}})
fmt.Println(out, *details.ActualCost())

Source code: example_cel_execution_cost_test.go


13. Advanced Topics: Error Handling & Name Resolution

Handling runtime errors and variable shadowing rules in macros:

Source code: example_cel_advanced_test.go


14. Go Native Structs (ext.NativeTypes)

Export Go structs into CEL and map struct field names using json, yaml, or cel struct tags:

type User struct {
	Name  string   `json:"name"`
	Age   int      `json:"age"`
	Roles []string `json:"roles"`
}

prg, _ := cel.Compile(`user.name == "Alice" && user.age >= 18`,
	cel.Variable("user", cel.ObjectType("examples.User")),
	ext.NativeTypes(reflect.TypeOf(User{}), ext.ParseStructTag("json")),
)
out, _, _ := prg.Eval(map[string]any{"user": User{Name: "Alice", Age: 30, Roles: []string{"admin"}}})
fmt.Println(out) // true

Source code: example_cel_native_structs_test.go


Running the Examples

Run all examples locally with go test:

go test -v ./examples/...

For interactive online examples, visit CEL by Example.

Documentation

Overview

Package examples provides example types and functions used in examples.

Example (Cel_Arithmetic)

Example_cel_Arithmetic showcases negation, basic operations, modulo, and precedence as documented in https://celbyexample.com/arithmetic/

exprs := []string{
	`-5`,
	`10 + 20`,
	`30 - 12`,
	`6 * 7`,
	`20 / 4`,
	`7 % 3`,
	`2 + 3 * 4`,
	`(2 + 3) * 4`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr)
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(cel.NoVars())
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
-5 -> -5
10 + 20 -> 30
30 - 12 -> 18
6 * 7 -> 42
20 / 4 -> 5
7 % 3 -> 1
2 + 3 * 4 -> 14
(2 + 3) * 4 -> 20
Example (Cel_Collections)

Example_cel_Collections showcases membership, indexing, search (exists), all, and filter on complex collections as documented in https://celbyexample.com/collections/

orderData := map[string]any{
	"id":       "ord-123",
	"customer": "alice@example.com",
	"tags":     []string{"express", "gift-wrapped"},
	"items": []map[string]any{
		{"name": "Laptop", "category": "electronics", "price": 999, "quantity": 1},
		{"name": "Cable", "category": "accessories", "price": 29, "quantity": 3},
	},
	"status": "pending",
}

exprs := []string{
	`"express" in order.tags`,
	`size(order.tags)`,
	`size(order.items)`,
	`order.tags[0]`,
	`order.items[0].name`,
	`order.items[0].price`,
	`order.tags.exists(t, t.startsWith("ex"))`,
	`order.items.exists(i, i.price > 500)`,
	`order.items.exists(i, i.category == "electronics" && i.price > 100)`,
	`order.tags.all(t, size(t) > 0)`,
	`order.items.all(i, i.quantity > 0)`,
	`order.items.all(i, i.price < 10000)`,
	`order.tags.filter(t, t != "express")`,
	`order.items.filter(i, i.price > 100)[0].name`,
	`order.items.filter(i, i.category == "electronics")[0].name`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr, cel.Variable("order", cel.DynType))
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(map[string]any{"order": orderData})
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
"express" in order.tags -> true
size(order.tags) -> 2
size(order.items) -> 2
order.tags[0] -> express
order.items[0].name -> Laptop
order.items[0].price -> 999
order.tags.exists(t, t.startsWith("ex")) -> true
order.items.exists(i, i.price > 500) -> true
order.items.exists(i, i.category == "electronics" && i.price > 100) -> true
order.tags.all(t, size(t) > 0) -> true
order.items.all(i, i.quantity > 0) -> true
order.items.all(i, i.price < 10000) -> true
order.tags.filter(t, t != "express") -> [gift-wrapped]
order.items.filter(i, i.price > 100)[0].name -> Laptop
order.items.filter(i, i.category == "electronics")[0].name -> Laptop
Example (Cel_CommonErrors)

Example_cel_CommonErrors showcases handling common runtime errors (division by zero, index out of bounds, missing key) as documented in https://celbyexample.com/common-errors/

vars := map[string]any{
	"m": map[string]int64{"a": 1},
	"l": []int64{10, 20},
}

exprs := []string{
	`1 / 0`,
	`l[5]`,
	`m["missing"]`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr,
		cel.Variable("m", cel.MapType(cel.StringType, cel.IntType)),
		cel.Variable("l", cel.ListType(cel.IntType)),
	)
	if err != nil {
		fmt.Printf("%s -> compile error: %v\n", expr, err)
		continue
	}
	_, _, err = prg.Eval(vars)
	if err != nil {
		fmt.Printf("%s -> runtime error: %v\n", expr, err)
	}
}
Output:
1 / 0 -> runtime error: division by zero
l[5] -> runtime error: index out of bounds: 5
m["missing"] -> runtime error: no such key: missing
Example (Cel_Comparison)

Example_cel_Comparison showcases equality and ordering comparison operators as documented in https://celbyexample.com/comparison/

exprs := []string{
	`10 == 10`,
	`10 != 20`,
	`"hello" == "hello"`,
	`"apple" < "banana"`,
	`5 < 10`,
	`10 <= 10`,
	`15 > 10`,
	`10 >= 10`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr)
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(cel.NoVars())
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
10 == 10 -> true
10 != 20 -> true
"hello" == "hello" -> true
"apple" < "banana" -> true
5 < 10 -> true
10 <= 10 -> true
15 > 10 -> true
10 >= 10 -> true
Example (Cel_Compile)

Example_cel_Compile showcases compiling a CEL expression with variable declarations

prg, err := cel.Compile(`"Hello world! I'm " + name + "."`,
	cel.Variable("name", cel.StringType),
)
if err != nil {
	log.Fatalf("cel.Compile() failed: %v", err)
}
out, _, err := prg.Eval(map[string]any{
	"name": "CEL",
})
if err != nil {
	log.Fatalf("prg.Eval() failed: %v", err)
}
fmt.Println(out)
Output:
Hello world! I'm CEL.
Example (Cel_Compile_options)

Example_cel_Compile_options showcases cel.Compile with extension options and multiple variables

prg, err := cel.Compile(`"%s! I'm %s.".format([greeting, name])`,
	ext.Strings(),
	cel.Variable("greeting", cel.StringType),
	cel.Variable("name", cel.StringType),
)
if err != nil {
	log.Fatalf("cel.Compile() failed: %v", err)
}
out, _, err := prg.Eval(map[string]any{
	"greeting": "Hello world",
	"name":     "CEL",
})
if err != nil {
	log.Fatalf("prg.Eval() failed: %v", err)
}
fmt.Println(out)
Output:
Hello world! I'm CEL.
Example (Cel_ContextEval)

Example_cel_ContextEval showcases evaluation cancellation and timeout using ContextEval

env, err := cel.NewEnv(
	cel.Variable("items", cel.ListType(cel.IntType)),
)
if err != nil {
	log.Fatalf("cel.NewEnv() failed: %v", err)
}

ast, iss := env.Compile(`items.map(x, x * 2).filter(x, x >= 50).size()`)
if iss.Err() != nil {
	log.Fatalf("env.Compile() failed: %v", iss.Err())
}

prg, err := env.Program(ast, cel.InterruptCheckFrequency(1))
if err != nil {
	log.Fatalf("env.Program() failed: %v", err)
}

items := make([]int64, 100)
for i := range items {
	items[i] = int64(i)
}
vars := map[string]any{"items": items}

// 1. Successful evaluation with an active context
out, _, err := prg.ContextEval(context.Background(), vars)
if err != nil {
	log.Fatalf("prg.ContextEval() failed: %v", err)
}
fmt.Println(out)

// 2. Interrupted evaluation with a canceled context
canceledCtx, cancel := context.WithCancel(context.Background())
cancel()

_, _, err = prg.ContextEval(canceledCtx, vars)
if err != nil {
	fmt.Printf("prg.ContextEval() error: %v\n", err)
}
Output:
75
prg.ContextEval() error: operation interrupted: context canceled
Example (Cel_CustomFunctions)

Example_cel_CustomFunctions showcases type safety and receiver syntax for custom functions

prg, err := cel.Compile(`name.greet()`,
	cel.Variable("name", cel.StringType),
	cel.Function("greet",
		cel.MemberOverload("string_greet",
			[]*cel.Type{cel.StringType},
			cel.StringType,
			cel.UnaryBinding(func(val ref.Val) ref.Val {
				return types.String("Hello, " + string(val.(types.String)))
			}),
		),
	),
)
if err != nil {
	log.Fatalf("cel.Compile() error: %v", err)
}

out, _, err := prg.Eval(map[string]any{
	"name": "Alice",
})
if err != nil {
	log.Fatalf("prg.Eval() error: %v", err)
}

fmt.Println(out)
Output:
Hello, Alice
Example (Cel_CustomMacros)

Example_cel_CustomMacros showcases defining custom AST transformation macros as documented in https://celbyexample.com/custom-macros/

// Define a custom macro "join_str(a, b)" that expands at compile time to "a + ' ' + b"
joinMacro := parser.NewGlobalMacro("join_str", 2, func(eh parser.ExprHelper, target ast.Expr, args []ast.Expr) (ast.Expr, *common.Error) {
	space := eh.NewLiteral(types.String(" "))
	firstConcat := eh.NewCall(operators.Add, args[0], space)
	return eh.NewCall(operators.Add, firstConcat, args[1]), nil
})

prg, err := cel.Compile(`join_str("Hello", "World")`, cel.Macros(joinMacro))
if err != nil {
	log.Fatalf("cel.Compile() error: %v", err)
}

out, _, err := prg.Eval(cel.NoVars())
if err != nil {
	log.Fatalf("prg.Eval() error: %v", err)
}

fmt.Println(out)
Output:
Hello World
Example (Cel_ExecutionCost)

Example_cel_ExecutionCost showcases static cost estimation with size hints and dynamic cost limits as documented in https://celbyexample.com/execution-cost/

package main

import (
	"fmt"
	"log"
	"strings"

	"cel.dev/cel-go/cel"
	"cel.dev/cel-go/checker"
	"cel.dev/cel-go/common/types/ref"
)

type exampleCostEstimator struct {
	hints map[string]uint64
}

func (e exampleCostEstimator) EstimateSize(element checker.AstNode) *checker.SizeEstimate {
	if l, ok := e.hints[strings.Join(element.Path(), ".")]; ok {
		return &checker.SizeEstimate{Min: 0, Max: l}
	}
	return nil
}

func (exampleCostEstimator) EstimateCallCost(function, overloadID string, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate {
	return nil
}

type exampleRuntimeCostEstimator struct{}

func (exampleRuntimeCostEstimator) CallCost(function, overloadID string, args []ref.Val, result ref.Val) *uint64 {
	return nil
}

// Example_cel_ExecutionCost showcases static cost estimation with size hints and dynamic cost limits
// as documented in https://celbyexample.com/execution-cost/
func main() {
	env, err := cel.NewEnv(
		cel.Variable("items", cel.ListType(cel.IntType)),
	)
	if err != nil {
		log.Fatalf("cel.NewEnv() error: %v", err)
	}

	ast, iss := env.Compile(`items.map(x, x * x).filter(x, x > 0).size()`)
	if iss.Err() != nil {
		log.Fatalln(iss.Err())
	}

	// 1. Static cost estimation with hints for "items" list length and "items.@items" element size
	estimator := exampleCostEstimator{
		hints: map[string]uint64{
			"items":        5,
			"items.@items": 10,
		},
	}
	costEstimate, err := env.EstimateCost(ast, estimator)
	if err != nil {
		log.Fatalf("env.EstimateCost() error: %v", err)
	}
	fmt.Printf("Estimated cost range: min=%d max=%d\n", costEstimate.Min, costEstimate.Max)

	// 2. Program with cost tracking and dynamic limit
	prg, err := env.Program(ast,
		cel.CostTracking(exampleRuntimeCostEstimator{}),
		cel.CostLimit(1000),
	)
	if err != nil {
		log.Fatalf("env.Program() error: %v", err)
	}

	out, details, err := prg.Eval(map[string]any{
		"items": []int64{1, 2, 3, 4, 5},
	})
	if err != nil {
		log.Fatalf("prg.Eval() error: %v", err)
	}

	fmt.Printf("Result: %v\n", out)
	if details.ActualCost() != nil {
		fmt.Printf("Actual cost: %d\n", *details.ActualCost())
	}

}
Output:
Estimated cost range: min=24 max=174
Result: 5
Actual cost: 174
Example (Cel_Lists)

Example_cel_Lists showcases list literals, indexing, membership, concatenation, and equality as documented in https://celbyexample.com/lists/

exprs := []string{
	`[1, 2, 3]`,
	`[]`,
	`[1, "two", true]`,
	`[[1, 2], [3, 4]]`,
	`size([1, 2, 3])`,
	`[1, 2, 3].size()`,
	`["a", "b", "c"][0]`,
	`["a", "b", "c"][2]`,
	`[[1, 2], [3, 4]][0][1]`,
	`2 in [1, 2, 3]`,
	`5 in [1, 2, 3]`,
	`[1, 2] + [3, 4]`,
	`[1, 2, 3] == [1, 2, 3]`,
	`[1, 2, 3] == [3, 2, 1]`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr)
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(cel.NoVars())
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
[1, 2, 3] -> [1, 2, 3]
[] -> []
[1, "two", true] -> [1, two, true]
[[1, 2], [3, 4]] -> [[1, 2], [3, 4]]
size([1, 2, 3]) -> 3
[1, 2, 3].size() -> 3
["a", "b", "c"][0] -> a
["a", "b", "c"][2] -> c
[[1, 2], [3, 4]][0][1] -> 2
2 in [1, 2, 3] -> true
5 in [1, 2, 3] -> false
[1, 2] + [3, 4] -> [1, 2, 3, 4]
[1, 2, 3] == [1, 2, 3] -> true
[1, 2, 3] == [3, 2, 1] -> false
Example (Cel_LogicAndConditions)

Example_cel_LogicAndConditions showcases logical operators, conditional (ternary) operator, and evaluation on user data as documented in https://celbyexample.com/logic-and-conditions/

userData := map[string]any{
	"is_active":  true,
	"is_admin":   false,
	"age":        25,
	"risk_score": 0.2,
}

exprs := []string{
	`user.is_active && user.age >= 18`,
	`user.is_admin || user.risk_score < 0.5`,
	`!user.is_admin`,
	`user.is_admin ? "full_access" : (user.is_active ? "standard_access" : "no_access")`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr, cel.Variable("user", cel.DynType))
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(map[string]any{"user": userData})
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
user.is_active && user.age >= 18 -> true
user.is_admin || user.risk_score < 0.5 -> true
!user.is_admin -> true
user.is_admin ? "full_access" : (user.is_active ? "standard_access" : "no_access") -> standard_access
Example (Cel_LogicalOperators)

Example_cel_LogicalOperators showcases logical AND, OR, NOT, and short-circuiting as documented in https://celbyexample.com/logical-operators/

exprs := []string{
	`true && false`,
	`true || false`,
	`!true`,
	`false && (1 / 0 == 0)`,
	`true || (1 / 0 == 0)`,
	`!false`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr)
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(cel.NoVars())
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
true && false -> false
true || false -> true
!true -> false
false && (1 / 0 == 0) -> false
true || (1 / 0 == 0) -> true
!false -> true
Example (Cel_Macros)

Example_cel_Macros showcases built-in CEL macros (has, all, exists, exists_one, filter, map) as documented in https://celbyexample.com/has/, /all/, /exists/, /exists-one/, /filter/, /map-macro/

vars := map[string]any{
	"msg":     map[string]any{"field": "present", "zero": 0},
	"numbers": []int64{1, 2, 3, 4, 5},
}

exprs := []string{
	`has(msg.field)`,
	`has(msg.missing)`,
	`numbers.all(x, x > 0)`,
	`numbers.all(x, x % 2 == 0)`,
	`numbers.exists(x, x == 3)`,
	`numbers.exists(x, x > 10)`,
	`numbers.exists_one(x, x == 3)`,
	`numbers.exists_one(x, x % 2 == 0)`,
	`numbers.filter(x, x % 2 == 0)`,
	`numbers.map(x, x * 10)`,
	`numbers.map(x, x % 2 == 0, x * 10)`,
}

opts := []cel.EnvOption{
	cel.Variable("msg", cel.MapType(cel.StringType, cel.DynType)),
	cel.Variable("numbers", cel.ListType(cel.IntType)),
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr, opts...)
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(vars)
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
has(msg.field) -> true
has(msg.missing) -> false
numbers.all(x, x > 0) -> true
numbers.all(x, x % 2 == 0) -> false
numbers.exists(x, x == 3) -> true
numbers.exists(x, x > 10) -> false
numbers.exists_one(x, x == 3) -> true
numbers.exists_one(x, x % 2 == 0) -> false
numbers.filter(x, x % 2 == 0) -> [2, 4]
numbers.map(x, x * 10) -> [10, 20, 30, 40, 50]
numbers.map(x, x % 2 == 0, x * 10) -> [20, 40]
Example (Cel_Maps)

Example_cel_Maps showcases map literals, size, field/key access, membership, and comparison as documented in https://celbyexample.com/maps/

exprs := []string{
	`{"a": 1, "b": 2}.a`,
	`size({"a": 1, "b": 2})`,
	`{1: "one", 2: "two"}[1]`,
	`{"nested": {"a": 1}}.nested.a`,
	`size({"a": 1, "b": 2, "c": 3})`,
	`{"a": 1, "b": 2}.size()`,
	`{"a": 1, "b": 2}["a"]`,
	`{"a": 1, "b": 2}.a`,
	`"a" in {"a": 1, "b": 2}`,
	`"c" in {"a": 1, "b": 2}`,
	`{"a": 1, "b": 2} == {"a": 1, "b": 2}`,
	`{"a": 1} == {"a": 2}`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr)
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(cel.NoVars())
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
{"a": 1, "b": 2}.a -> 1
size({"a": 1, "b": 2}) -> 2
{1: "one", 2: "two"}[1] -> one
{"nested": {"a": 1}}.nested.a -> 1
size({"a": 1, "b": 2, "c": 3}) -> 3
{"a": 1, "b": 2}.size() -> 2
{"a": 1, "b": 2}["a"] -> 1
{"a": 1, "b": 2}.a -> 1
"a" in {"a": 1, "b": 2} -> true
"c" in {"a": 1, "b": 2} -> false
{"a": 1, "b": 2} == {"a": 1, "b": 2} -> true
{"a": 1} == {"a": 2} -> false
Example (Cel_MemberOverload)

Example_cel_MemberOverload showcases defining custom receiver/member functions with cel.MemberOverload as documented in https://celbyexample.com/custom-functions/

prg, err := cel.Compile(`i.greet(you)`,
	cel.Lib(customGreetLib{}),
)
if err != nil {
	log.Fatalf("cel.Compile() error: %v", err)
}

out, _, err := prg.Eval(map[string]any{
	"i":   "CEL",
	"you": "world",
})
if err != nil {
	log.Fatalf("prg.Eval() error: %v", err)
}

fmt.Println(out)
Output:
Hello world! Nice to meet you, I'm CEL.
Example (Cel_NameResolution)

Example_cel_NameResolution showcases scope resolution order and macro variable shadowing as documented in https://celbyexample.com/name-resolution/

vars := map[string]any{
	"x":     100,
	"items": []int64{1, 2, 3},
}

// In items.map(x, x * 2), the iteration variable 'x' shadows the outer variable 'x'
prg, err := cel.Compile(`items.map(x, x * 2)`,
	cel.Variable("x", cel.IntType),
	cel.Variable("items", cel.ListType(cel.IntType)),
)
if err != nil {
	fmt.Printf("cel.Compile() error: %v\n", err)
	return
}
out, _, err := prg.Eval(vars)
if err != nil {
	fmt.Printf("prg.Eval() error: %v\n", err)
	return
}

fmt.Printf("Macro iteration variable shadows outer x: %v\n", out)
Output:
Macro iteration variable shadows outer x: [2, 4, 6]
Example (Cel_NativeTypes)

Example_cel_NativeTypes showcases evaluating Go native structs using ext.NativeTypes() with json struct tags

package main

import (
	"fmt"
	"log"
	"reflect"

	"cel.dev/cel-go/cel"
	"cel.dev/cel-go/examples"
	"cel.dev/cel-go/ext"
)

func main() {
	u := examples.User{
		Name:  "Alice",
		Age:   30,
		Roles: []string{"admin", "editor"},
	}

	exprs := []string{
		`user.name == "Alice"`,
		`user.age >= 18`,
		`"admin" in user.roles`,
		`user.name + " (" + string(user.age) + ")"`,
	}

	for _, expr := range exprs {
		prg, err := cel.Compile(expr,
			cel.Variable("user", cel.ObjectType("examples.User")),
			ext.NativeTypes(reflect.TypeFor[examples.User](), ext.ParseStructTag("json")),
		)
		if err != nil {
			log.Fatalf("cel.Compile() error for %q: %v", expr, err)
		}
		out, _, err := prg.Eval(map[string]any{"user": u})
		if err != nil {
			log.Fatalf("prg.Eval() error for %q: %v", expr, err)
		}
		fmt.Printf("%s -> %v\n", expr, out)
	}

}
Output:
user.name == "Alice" -> true
user.age >= 18 -> true
"admin" in user.roles -> true
user.name + " (" + string(user.age) + ")" -> Alice (30)
Example (Cel_NativeTypes_structTags)

Example_cel_NativeTypes_structTags showcases mapping struct field names via cel tags

package main

import (
	"fmt"
	"log"
	"reflect"

	"cel.dev/cel-go/cel"
	"cel.dev/cel-go/examples"
	"cel.dev/cel-go/ext"
)

func main() {
	acc := examples.Account{
		ID:        1001,
		OwnerName: "Bob",
	}

	prg, err := cel.Compile(`acc.owner == "Bob" && acc.id == 1001`,
		cel.Variable("acc", cel.ObjectType("examples.Account")),
		ext.NativeTypes(reflect.TypeFor[examples.Account](), ext.ParseStructTags(true)),
	)
	if err != nil {
		log.Fatalf("cel.Compile() error: %v", err)
	}
	out, _, err := prg.Eval(map[string]any{"acc": acc})
	if err != nil {
		log.Fatalf("prg.Eval() error: %v", err)
	}
	fmt.Println(out)

}
Output:
true
Example (Cel_Null)

Example_cel_Null showcases null literal and null equality checks as documented in https://celbyexample.com/null/

exprs := []string{
	`null`,
	`val == null`,
	`val != null`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr, cel.Variable("val", cel.DynType))
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(map[string]any{"val": nil})
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
null -> 0
val == null -> true
val != null -> false
Example (Cel_Overload)

Example_cel_Overload showcases defining custom global functions with cel.Overload as documented in https://celbyexample.com/custom-functions/

prg, err := cel.Compile(`shake_hands(i,you)`,
	cel.Variable("i", cel.StringType),
	cel.Variable("you", cel.StringType),
	cel.Function("shake_hands",
		cel.Overload("shake_hands_string_string",
			[]*cel.Type{cel.StringType, cel.StringType},
			cel.StringType,
			cel.BinaryBinding(func(lhs, rhs ref.Val) ref.Val {
				return types.String(
					fmt.Sprintf("%s and %s are shaking hands.", lhs, rhs))
			}),
		),
	),
)
if err != nil {
	log.Fatalf("cel.Compile() error: %v", err)
}

out, _, err := prg.Eval(map[string]any{
	"i":   "CEL",
	"you": "world",
})
if err != nil {
	log.Fatalf("prg.Eval() error: %v", err)
}

fmt.Println(out)
Output:
CEL and world are shaking hands.
Example (Cel_Primitives)

Example_cel_Primitives showcases int, uint, double, bool, bytes, and string primitive literals as documented in https://celbyexample.com/primitives/

exprs := []string{
	`42`,
	`-10`,
	`42u`,
	`3.14159`,
	`1e-3`,
	`true`,
	`false`,
	`"hello CEL"`,
	`b"hello"`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr)
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(cel.NoVars())
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
42 -> 42
-10 -> -10
42u -> 42
3.14159 -> 3.14159
1e-3 -> 0.001
true -> true
false -> false
"hello CEL" -> hello CEL
b"hello" -> [104 101 108 108 111]
Example (Cel_ProtocolBuffers)

Example_cel_ProtocolBuffers showcases evaluating protobuf messages, enum values, field presence (has), and default values as documented in https://celbyexample.com/protocol-buffers/

userMsg := &proto3pb.TestAllTypes{
	SingleString: "Alice",
	SingleInt64:  42,
	NestedType:   &proto3pb.TestAllTypes_SingleNestedEnum{SingleNestedEnum: proto3pb.TestAllTypes_BAR},
}

exprs := []string{
	`user.single_string`,
	`user.single_int64 == 42`,
	`user.single_nested_enum == google.expr.proto3.test.TestAllTypes.NestedEnum.BAR`,
	`has(user.single_string)`,
	`has(user.single_bytes)`,
	`user.single_bool`,
}

opts := []cel.EnvOption{
	cel.Types(userMsg),
	cel.Variable("user", cel.ObjectType("google.expr.proto3.test.TestAllTypes")),
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr, opts...)
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(map[string]any{"user": userMsg})
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
user.single_string -> Alice
user.single_int64 == 42 -> true
user.single_nested_enum == google.expr.proto3.test.TestAllTypes.NestedEnum.BAR -> true
has(user.single_string) -> true
has(user.single_bytes) -> false
user.single_bool -> false
Example (Cel_Strings)

Example_cel_Strings showcases built-in string manipulation functions as documented in https://celbyexample.com/strings/

exprs := []string{
	`"hello" + " " + "world"`,
	`size("hello")`,
	`"hello".size()`,
	`"hello world".contains("world")`,
	`"hello world".endsWith("world")`,
	`"hello world".startsWith("hello")`,
	`"hello".matches("^[a-z]+$")`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr)
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(cel.NoVars())
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
"hello" + " " + "world" -> hello world
size("hello") -> 5
"hello".size() -> 5
"hello world".contains("world") -> true
"hello world".endsWith("world") -> true
"hello world".startsWith("hello") -> true
"hello".matches("^[a-z]+$") -> true
Example (Cel_StringsAndNumbers)

Example_cel_StringsAndNumbers showcases string functions, concatenation, and numeric comparisons on user data as documented in https://celbyexample.com/strings-and-numbers/

userData := map[string]any{
	"name":  "Alice",
	"roles": []string{"admin", "editor", "viewer"},
	"age":   30,
	"score": 95.5,
}

exprs := []string{
	`user.name.endsWith("ice")`,
	`"admin" in user.roles`,
	`user.age >= 18`,
	`user.score > 90.0`,
	`user.name + " (" + string(user.age) + ")"`,
	`size(user.roles)`,
	`user.name.contains("lic")`,
	`user.name.startsWith("Al")`,
	`user.name.matches("^[A-Z][a-z]+$")`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr, cel.Variable("user", cel.DynType))
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(map[string]any{"user": userData})
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
user.name.endsWith("ice") -> true
"admin" in user.roles -> true
user.age >= 18 -> true
user.score > 90.0 -> true
user.name + " (" + string(user.age) + ")" -> Alice (30)
size(user.roles) -> 3
user.name.contains("lic") -> true
user.name.startsWith("Al") -> true
user.name.matches("^[A-Z][a-z]+$") -> true
Example (Cel_StringsExtension)

Example_cel_StringsExtension showcases string extension library functions (ext.Strings()) as documented in https://celbyexample.com/strings/

exprs := []string{
	`"hello world".replace("world", "CEL")`,
	`"hello world".substring(0, 5)`,
	`"HELLO".lowerAscii()`,
	`"hello".upperAscii()`,
	`"  hello  ".trim()`,
	`"hello".charAt(0)`,
	`"hello world".indexOf("world")`,
	`"a,b,c".split(",")`,
	`["a", "b", "c"].join("-")`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr, ext.Strings())
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(cel.NoVars())
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
"hello world".replace("world", "CEL") -> hello CEL
"hello world".substring(0, 5) -> hello
"HELLO".lowerAscii() -> hello
"hello".upperAscii() -> HELLO
"  hello  ".trim() -> hello
"hello".charAt(0) -> h
"hello world".indexOf("world") -> 6
"a,b,c".split(",") -> [a, b, c]
["a", "b", "c"].join("-") -> a-b-c
Example (Cel_Ternary)

Example_cel_Ternary showcases ternary conditional expressions as documented in https://celbyexample.com/ternary/

exprs := []string{
	`true ? "yes" : "no"`,
	`false ? 1 : 2`,
	`10 > 5 ? "greater" : "lesser"`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr)
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(cel.NoVars())
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
true ? "yes" : "no" -> yes
false ? 1 : 2 -> 2
10 > 5 ? "greater" : "lesser" -> greater
Example (Cel_Time)

Example_cel_Time showcases timezones, timestamp components, and epoch conversions as documented in https://celbyexample.com/time/

exprs := []string{
	`timestamp("2024-01-15T10:30:45Z").getHours("America/New_York")`,
	`timestamp("2024-01-15T10:30:45Z").getDayOfWeek("UTC")`,
	`duration("3600s")`,
	`duration("-500ms")`,
	`timestamp(1705314645)`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr)
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(cel.NoVars())
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
timestamp("2024-01-15T10:30:45Z").getHours("America/New_York") -> 5
timestamp("2024-01-15T10:30:45Z").getDayOfWeek("UTC") -> 1
duration("3600s") -> 1h0m0s
duration("-500ms") -> -500ms
timestamp(1705314645) -> 2024-01-15 10:30:45 +0000 UTC
Example (Cel_TimestampsAndDurations)

Example_cel_TimestampsAndDurations showcases timestamps, durations, arithmetic, and field access as documented in https://celbyexample.com/timestamps-and-durations/

exprs := []string{
	`timestamp("2024-01-15T10:30:45Z")`,
	`duration("1h30m")`,
	`timestamp("2024-01-15T10:30:45Z") + duration("1h")`,
	`timestamp("2024-01-15T10:30:45Z") - timestamp("2024-01-15T09:30:45Z")`,
	`timestamp("2024-01-15T10:30:45Z").getFullYear()`,
	`timestamp("2024-01-15T10:30:45Z").getMonth()`,
	`timestamp("2024-01-15T10:30:45Z").getDayOfMonth()`,
	`duration("1h").getHours()`,
	`duration("90m").getMinutes()`,
	`timestamp("2024-01-15T10:30:45Z") > timestamp("2024-01-01T00:00:00Z")`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr)
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(cel.NoVars())
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
timestamp("2024-01-15T10:30:45Z") -> 2024-01-15 10:30:45 +0000 UTC
duration("1h30m") -> 1h30m0s
timestamp("2024-01-15T10:30:45Z") + duration("1h") -> 2024-01-15 11:30:45 +0000 UTC
timestamp("2024-01-15T10:30:45Z") - timestamp("2024-01-15T09:30:45Z") -> 1h0m0s
timestamp("2024-01-15T10:30:45Z").getFullYear() -> 2024
timestamp("2024-01-15T10:30:45Z").getMonth() -> 0
timestamp("2024-01-15T10:30:45Z").getDayOfMonth() -> 14
duration("1h").getHours() -> 1
duration("90m").getMinutes() -> 90
timestamp("2024-01-15T10:30:45Z") > timestamp("2024-01-01T00:00:00Z") -> true
Example (Cel_TransformingData)

Example_cel_TransformingData showcases building maps, transforming lists with map(), filtering and transforming, and combining techniques as documented in https://celbyexample.com/transforming-data/

orderData := map[string]any{
	"id":           "ord-123",
	"customer":     "alice@example.com",
	"customer_age": 30,
	"tags":         []string{"express", "gift-wrapped"},
	"items": []map[string]any{
		{"name": "Laptop", "category": "electronics", "price": 999, "quantity": 1},
		{"name": "Cable", "category": "accessories", "price": 29, "quantity": 3},
	},
	"status": "pending",
}

exprs := []string{
	`{"tags": order.tags, "is_adult": order.customer_age >= 18}.is_adult`,
	`{"customer": order.customer, "item_count": size(order.items)}.item_count`,
	`order.tags.map(t, t + ":enabled")`,
	`order.items.map(i, i.name)`,
	`order.tags.map(t, t != "express", t + ":applied")`,
	`order.items.map(i, i.price > 100, i.name)`,
	`{"id": order.id, "electronics": order.items.filter(i, i.category == "electronics").map(i, i.name)}.electronics`,
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr, cel.Variable("order", cel.DynType))
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(map[string]any{"order": orderData})
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
{"tags": order.tags, "is_adult": order.customer_age >= 18}.is_adult -> true
{"customer": order.customer, "item_count": size(order.items)}.item_count -> 2
order.tags.map(t, t + ":enabled") -> [express:enabled, gift-wrapped:enabled]
order.items.map(i, i.name) -> [Laptop, Cable]
order.tags.map(t, t != "express", t + ":applied") -> [gift-wrapped:applied]
order.items.map(i, i.price > 100, i.name) -> [Laptop]
{"id": order.id, "electronics": order.items.filter(i, i.category == "electronics").map(i, i.name)}.electronics -> [Laptop]
Example (Cel_TypeConversions)

Example_cel_TypeConversions showcases type casting functions (int, uint, double, string, bytes, dyn) as documented in https://celbyexample.com/type-conversions/

package main

import (
	"fmt"
	"log"

	"cel.dev/cel-go/cel"
)

func main() {
	exprs := []string{
		`int("123")`,
		`int(3.14)`,
		`uint(42)`,
		`double("3.14")`,
		`double(100)`,
		`string(42)`,
		`string(true)`,
		`bytes("hello")`,
		`dyn("anything")`,
	}

	for _, expr := range exprs {
		prg, err := cel.Compile(expr)
		if err != nil {
			log.Fatalf("cel.Compile() error for %q: %v", expr, err)
		}
		out, _, err := prg.Eval(cel.NoVars())
		if err != nil {
			log.Fatalf("prg.Eval() error for %q: %v", expr, err)
		}
		fmt.Printf("%s -> %v\n", expr, out)
	}

}
Output:
int("123") -> 123
int(3.14) -> 3
uint(42) -> 42
double("3.14") -> 3.14
double(100) -> 100
string(42) -> 42
string(true) -> true
bytes("hello") -> [104 101 108 108 111]
dyn("anything") -> anything
Example (Cel_TypeIntrospection)

Example_cel_TypeIntrospection showcases type identification using type(x) as documented in https://celbyexample.com/type-introspection/

package main

import (
	"fmt"
	"log"

	"cel.dev/cel-go/cel"
)

func main() {
	exprs := []string{
		`type("hello") == string`,
		`type(42) == int`,
		`type(3.14) == double`,
		`type(true) == bool`,
		`type([1, 2, 3])`,
		`type({"a": 1})`,
	}

	for _, expr := range exprs {
		prg, err := cel.Compile(expr)
		if err != nil {
			log.Fatalf("cel.Compile() error for %q: %v", expr, err)
		}
		out, _, err := prg.Eval(cel.NoVars())
		if err != nil {
			log.Fatalf("prg.Eval() error for %q: %v", expr, err)
		}
		fmt.Printf("%s -> %v\n", expr, out)
	}

}
Output:
type("hello") == string -> true
type(42) == int -> true
type(3.14) == double -> true
type(true) == bool -> true
type([1, 2, 3]) -> list(dyn)
type({"a": 1}) -> map(dyn, dyn)
Example (Cel_WellKnownTypes)

Example_cel_WellKnownTypes showcases wrapper types (StringValue, BoolValue) and google.protobuf.Struct as documented in https://celbyexample.com/well-known-types/

structVal, _ := structpb.NewStruct(map[string]any{
	"key":   "value",
	"count": 10,
})

vars := map[string]any{
	"wrapped_str": wrapperspb.String("hello"),
	"json_obj":    structVal,
}

exprs := []string{
	`wrapped_str == "hello"`,
	`json_obj.key == "value"`,
	`json_obj.count == 10`,
}

opts := []cel.EnvOption{
	cel.Types(structVal),
	cel.Variable("wrapped_str", cel.ObjectType("google.protobuf.StringValue")),
	cel.Variable("json_obj", cel.ObjectType("google.protobuf.Struct")),
}

for _, expr := range exprs {
	prg, err := cel.Compile(expr, opts...)
	if err != nil {
		log.Fatalf("cel.Compile() error for %q: %v", expr, err)
	}
	out, _, err := prg.Eval(vars)
	if err != nil {
		log.Fatalf("prg.Eval() error for %q: %v", expr, err)
	}
	fmt.Printf("%s -> %v\n", expr, out)
}
Output:
wrapped_str == "hello" -> true
json_obj.key == "value" -> true
json_obj.count == 10 -> true

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Account

type Account struct {
	ID        int64  `cel:"id"`
	OwnerName string `cel:"owner"`
}

Account is a sample account struct with fields tagged for CEL field access.

type User

type User struct {
	Name  string   `json:"name"`
	Age   int      `json:"age"`
	Roles []string `json:"roles"`
}

User is a sample user struct with fields tagged for JSON serialization.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL