代码简介
年龄大于20且商品价格大于30可以进行购买
代码
package main
import (
"fmt"
"log"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
)
var (
userMap = map[int64]int{
1: 20,
}
goodsMap = map[int64]int{
1: 30,
}
)
func age(userID int64) int {
return userMap[userID]
}
func price(goodsID int64) int {
return goodsMap[goodsID]
}
func main() {
env, err := cel.NewEnv(
cel.Variable("user_id", cel.IntType),
cel.Function("age",
cel.Overload("age",
[]*cel.Type{cel.IntType},
cel.IntType,
cel.UnaryBinding(func(val ref.Val) ref.Val {
return types.Int(age(val.Value().(int64)))
},
),
),
),
cel.Variable("goods_id", cel.IntType),
cel.Function("price",
cel.Overload("price",
[]*cel.Type{cel.IntType},
cel.IntType,
cel.UnaryBinding(func(val ref.Val) ref.Val {
return types.Int(price(val.Value().(int64)))
},
),
),
),
)
if err != nil {
log.Fatalf("environment error: %+v\n", err)
}
ast, iss := env.Compile(`age(user_id) >= 20 && price(goods_id) >= 30`)
if iss.Err() != nil {
log.Fatalln(iss.Err())
}
prg, err := env.Program(ast)
if err != nil {
log.Fatalf("Program error: %+v\n", err)
}
out, _, err := prg.Eval(map[string]any{
"user_id": 1,
"goods_id": 1,
})
if err != nil {
log.Fatalf("Eval error: %+v\n", err)
}
fmt.Println(out)
}
网友评论