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

Function exercise5

codelab/solution/codelab.go:202–233  ·  view source on GitHub ↗

exercise5 covers how to build complex objects as CEL literals. Given the input `now`, construct a JWT with an expiry of 5 minutes.

()

Source from the content-addressed store, hash-verified

200//
201// Given the input `now`, construct a JWT with an expiry of 5 minutes.
202func exercise5() {
203 fmt.Println("=== Exercise 5: Building JSON ===\n")
204 // Note the quoted keys in the CEL map literal. For proto messages the
205 // field names are unquoted as they represent well-defined identifiers.
206 env, _ := cel.NewEnv(
207 cel.Variable("now", cel.TimestampType),
208 )
209 ast := compile(env, `
210 {'aud': 'my-project',
211 'exp': now + duration('300s'),
212 'extra_claims': {
213 'group': 'admin'
214 },
215 'iat': now,
216 'iss': 'auth.acme.com:12350',
217 'nbf': now,
218 'sub': 'serviceAccount:delegate@acme.co'
219 }`,
220 cel.MapType(cel.StringType, cel.DynType))
221
222 program, _ := env.Program(ast)
223 out, _, _ := eval(
224 program,
225 map[string]any{
226 "now": time.Now(),
227 },
228 )
229 // The output of the program is a CEL map type, but it can be converted
230 // to a JSON representation using the `ConvertToNative` method.
231 fmt.Printf("------ type conversion ------\n%v\n", valueToJSON(out))
232 fmt.Println()
233}
234
235// exercise6 describes how to build proto message types within CEL.
236//

Callers 1

mainFunction · 0.70

Calls 6

ProgramMethod · 0.95
NewEnvFunction · 0.92
VariableFunction · 0.92
compileFunction · 0.70
evalFunction · 0.70
valueToJSONFunction · 0.70

Tested by

no test coverage detected