MCPcopy Create free account
hub / github.com/cel-expr/cel-go / Example_statefulOverload

Function Example_statefulOverload

cel/cel_example_test.go:122–179  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

120}
121
122func Example_statefulOverload() {
123 // makeFetch produces a consistent function signature with a different function
124 // implementation depending on the provided context.
125 makeFetch := func(ctx any) cel.EnvOption {
126 fn := func(arg ref.Val) ref.Val {
127 return types.NewErr("stateful context not bound")
128 }
129 if ctx != nil {
130 fn = func(resource ref.Val) ref.Val {
131 return types.DefaultTypeAdapter.NativeToValue(
132 ctx.(context.Context).Value(contextString(string(resource.(types.String)))),
133 )
134 }
135 }
136 return cel.Function("fetch",
137 cel.Overload("fetch_string",
138 []*cel.Type{cel.StringType}, cel.StringType,
139 cel.UnaryBinding(fn),
140 ),
141 )
142 }
143
144 // The base environment declares the fetch function with a dummy binding that errors
145 // if it is invoked without being replaced by a subsequent call to `baseEnv.Extend`
146 baseEnv, err := cel.NewEnv(
147 // Identifiers used within this expression.
148 cel.Variable("resource", cel.StringType),
149 // Function to fetch a resource.
150 // fetch(resource)
151 makeFetch(nil),
152 )
153 if err != nil {
154 log.Fatalf("environment creation error: %s\n", err)
155 }
156 ast, iss := baseEnv.Compile("fetch('my-resource') == 'my-value'")
157 if iss.Err() != nil {
158 log.Fatalf("Compile() failed: %v", iss.Err())
159 }
160
161 // The runtime environment extends the base environment with a contextual binding for
162 // the 'fetch' function.
163 ctx := context.WithValue(context.TODO(), contextString("my-resource"), "my-value")
164 runtimeEnv, err := baseEnv.Extend(makeFetch(ctx))
165 if err != nil {
166 log.Fatalf("baseEnv.Extend() failed with error: %s\n", err)
167 }
168 prg, err := runtimeEnv.Program(ast)
169 if err != nil {
170 log.Fatalf("runtimeEnv.Program() error: %s\n", err)
171 }
172 out, _, err := prg.Eval(cel.NoVars())
173 if err != nil {
174 log.Fatalf("runtime error: %s\n", err)
175 }
176
177 fmt.Println(out)
178 // Output:true
179}

Callers

nothing calls this directly

Calls 15

CompileMethod · 0.95
ExtendMethod · 0.95
NewErrFunction · 0.92
FunctionFunction · 0.92
OverloadFunction · 0.92
UnaryBindingFunction · 0.92
NewEnvFunction · 0.92
VariableFunction · 0.92
NoVarsFunction · 0.92
contextStringTypeAlias · 0.85
ErrMethod · 0.80
ProgramMethod · 0.80

Tested by

no test coverage detected