Skip to content

jahvon/expression

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Expression

Go Report Card Go Reference

A Go package that provides powerful expression evaluation and templating capabilities, built on top of the expr language.

Installation

go get github.com/jahvon/expression

Basic Expression Evaluation

package 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
}

Template Processing

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)
}

Expression Language

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 exists
  • dirExists(path) - Check if path is a directory
  • isFile(path) - Check if path is a file
  • isDir(path) - Check if path is a directory
  • basename(path) - Get filename from path
  • dirname(path) - Get directory from path
  • readFile(path) - Read file contents as string
  • fileSize(path) - Get file size in bytes
  • fileModTime(path) - Get file modification time
  • fileAge(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"

Contributing

Contributions are welcome! Please ensure all tests pass:

go test ./...

About

Go string expression and text/template helpers using Expr language

Resources

License

Stars

Watchers

Forks

Languages