A Go package that provides powerful expression evaluation and templating capabilities, built on top of the expr language.
Installation
go get github.com/jahvon/expressionpackage main
import (
"fmt"
"github.com/jahvon/expression"
)
func main() {
// Create data context
data := map[string]interface{}{
"name": "John",
"age": 30,
}
// Evaluate expressions
result, err := expression.Evaluate("name + ' is ' + string(age)", data)
if err != nil {
panic(err)
}
fmt.Println(result) // Output: John is 30
// Check truthiness
truthy, err := expression.IsTruthy("age > 18", data)
if err != nil {
panic(err)
}
fmt.Println(truthy) // Output: true
}The template engine extends Go's text/template with Expr expression evaluation:
package main
import (
"fmt"
"github.com/jahvon/expression"
)
func main() {
data := map[string]interface{}{
"user": "Alice",
"enabled": true,
"items": []string{"apple", "banana", "orange"},
}
tmpl := expression.NewTemplate("example", data)
templateText := `
Hello {{user}}!
It's {{$("time")}}
{{if enabled}}
Your account is active.
Items:
{{range items}}
- {{.}}
{{end}}
{{end}}
`
err := tmpl.Parse(templateText)
if err != nil {
panic(err)
}
result, err := tmpl.ExecuteToString()
if err != nil {
panic(err)
}
fmt.Println(result)
}See the Expr Language Definition for the full syntax and capabilities of the expression language.
Additionally, the following functions are provided:
File Helpers:
fileExists(path)- Check if file/directory existsdirExists(path)- Check if path is a directoryisFile(path)- Check if path is a fileisDir(path)- Check if path is a directorybasename(path)- Get filename from pathdirname(path)- Get directory from pathreadFile(path)- Read file contents as stringfileSize(path)- Get file size in bytesfileModTime(path)- Get file modification timefileAge(path)- Get duration since last modified
// Example usage
result, _ := expression.Evaluate(`fileExists("/path/file.txt") && fileSize("/path/file.txt") > 0`, nil)
filename, _ := expression.EvaluateString(`basename("/home/user/doc.txt")`, nil) // "doc.txt"Contributions are welcome! Please ensure all tests pass:
go test ./...