Created
October 24, 2023 15:26
-
-
Save bastjan/a4f457358c29d06319477ba41e80886a to your computer and use it in GitHub Desktop.
go-jsonnet native funtion callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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