Expr 是一个专为 Go 语言设计的表达式求值库,旨在通过简洁的语法实现动态配置、业务规则和条件判断。它强调安全性(内存安全、无副作用、无死循环)、高性能(基于字节码虚拟机优化)和无缝 Go 集成(直接复用 Go 类型,静态类型检查)。
string+int直接报错)。all、filter、map等)和操作符。 • 清晰的错误提示,快速定位语法或逻辑问题。安装:
go get github.com/expr-lang/expr 示例 1:动态字符串生成
env := map[string]interface{}{ "greet":"Hello, %v!", "names":[]string{"world","you"}, "sprintf": fmt.Sprintf, } code :=`sprintf(greet, names[0])`// 输出 "Hello, world!" program, _ := expr.Compile(code, expr.Env(env)) output, _ := expr.Run(program, env) fmt.Println(output) 示例 2:业务规则验证
type Tweetstruct{Lenint} type Envstruct{Tweets[]Tweet} code :=`all(Tweets, {.Len <= 240})`// 检查所有推文长度 ≤240 program, _ := expr.Compile(code, expr.Env(Env{})) env :=Env{Tweets:[]Tweet{{42},{98},{69}}} output, _ := expr.Run(program, env)// 输出 true • Uber、GoDaddy:动态配置电商/服务策略 • ByteDance、Aviasales:业务规则引擎 • Argo Rollouts、CoreDNS:基础设施逻辑控制 • Chaos Mesh、CrowdSec:安全与混沌工程
Expr 凭借其安全性、性能和Go 原生友好性,成为动态规则场景的优选方案。若你的项目需要灵活表达式求值(如用户自定义条件、实时策略调整),Expr 能以极低成本接入,避免重复造轮子的同时保障代码健壮性。