| 1 | // Copyright 2020 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package examples |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "log" |
| 20 | |
| 21 | "github.com/google/cel-go/cel" |
| 22 | "github.com/google/cel-go/common/types" |
| 23 | "github.com/google/cel-go/common/types/ref" |
| 24 | ) |
| 25 | |
| 26 | func Example_cel_MemberOverload() { |
| 27 | env, err := cel.NewEnv(cel.Lib(customLib{})) |
| 28 | if err != nil { |
| 29 | log.Fatalf("environment creation error: %v\n", err) |
| 30 | } |
| 31 | // Check iss for error in both Parse and Check. |
| 32 | ast, iss := env.Compile(`i.greet(you)`) |
| 33 | if iss.Err() != nil { |
| 34 | log.Fatalln(iss.Err()) |
| 35 | } |
| 36 | prg, err := env.Program(ast) |
| 37 | if err != nil { |
| 38 | log.Fatalf("Program creation error: %v\n", err) |
| 39 | } |
| 40 | |
| 41 | out, _, err := prg.Eval(map[string]any{ |
| 42 | "i": "CEL", |
| 43 | "you": "world", |
| 44 | }) |
| 45 | if err != nil { |
| 46 | log.Fatalf("Evaluation error: %v\n", err) |
| 47 | } |
| 48 | |
| 49 | fmt.Println(out) |
| 50 | // Output:Hello world! Nice to meet you, I'm CEL. |
| 51 | } |
| 52 | |
| 53 | type customLib struct{} |
| 54 | |
| 55 | func (customLib) CompileOptions() []cel.EnvOption { |
| 56 | return []cel.EnvOption{ |
| 57 | cel.Variable("i", cel.StringType), |
| 58 | cel.Variable("you", cel.StringType), |
| 59 | cel.Function("greet", |
| 60 | cel.MemberOverload("string_greet_string", |
| 61 | []*cel.Type{cel.StringType, cel.StringType}, |
| 62 | cel.StringType, |
| 63 | cel.BinaryBinding(func(lhs, rhs ref.Val) ref.Val { |
| 64 | return types.String( |
| 65 | fmt.Sprintf("Hello %s! Nice to meet you, I'm %s.\n", rhs, lhs)) |
| 66 | }), |
| 67 | ), |
| 68 | ), |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | func (customLib) ProgramOptions() []cel.ProgramOption { |
| 73 | return []cel.ProgramOption{} |
| 74 | } |