Skip to content

Instantly share code, notes, and snippets.

@bastjan
Created October 24, 2023 15:26
Show Gist options
  • Save bastjan/a4f457358c29d06319477ba41e80886a to your computer and use it in GitHub Desktop.
Save bastjan/a4f457358c29d06319477ba41e80886a to your computer and use it in GitHub Desktop.
go-jsonnet native funtion callback
package main
import (
"fmt"
"log"
"github.com/google/go-jsonnet"
"github.com/google/go-jsonnet/ast"
)
func main() {
vm := jsonnet.MakeVM()
snippet := `std.native("gimme")("that") + {
person1: {
name: "Alice",
welcome: "Hello " + self.name + "!",
},
person2: self.person1 { name: "Bob" },
}`
vm.NativeFunction(&jsonnet.NativeFunction{
Name: "gimme",
Func: func(args []interface{}) (interface{}, error) {
return map[string]interface{}{"gimme": args[0]}, nil
},
Params: ast.Identifiers{"what"},
})
jsonStr, err := vm.EvaluateAnonymousSnippet("example1.jsonnet", snippet)
if err != nil {
log.Fatal(err)
}
fmt.Println(jsonStr)
/*
{
"gimme": "that",
"person1": {
"name": "Alice",
"welcome": "Hello Alice!"
},
"person2": {
"name": "Bob",
"welcome": "Hello Bob!"
}
}
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment