-
Notifications
You must be signed in to change notification settings - Fork 319
Open
Description
I found a way to invoke tengo script function from Go and retrieve result.
Documenting it for others.
package main
import (
"fmt"
"strings"
"time"
"github.com/d5/tengo/v2"
)
func main() {
// Tengo source which has function defined
source := `
greetUser := func(name) {
return ["Hello", name]
}
`
// How to invoke the function and collect the return value securely.
// Define random result variable (overcomes collision with source variables).
resultVarName := fmt.Sprintf("__result_%d", time.Now().UnixNano())
// Target method to call with arguments
methodName := "greetUser"
methodArgs := []string{`"Yourname"`}
// Rebuild source
fullSource := source + fmt.Sprintf("\n%s := %s(%s)",
resultVarName, methodName, strings.Join(methodArgs, ","))
script := tengo.NewScript([]byte(fullSource))
if compiled, err := script.Compile(); err != nil {
panic(err)
} else {
if err = compiled.Run(); err != nil {
panic(err)
}
result := compiled.Get(resultVarName)
fmt.Printf("%#v", result.Value())
}
}
Metadata
Metadata
Assignees
Labels
No labels