The cue
command allows non-CUE data to be “placed” at a specific location in
its evaluation with the --path
/-l
flag.
This guide demonstrates how to achieve the same result using the Go API.
Set up the environment
If you don’t already have CUE or Go modules, initialize them:
$ cue mod init cue.example
$ go mod init go.example
...
Create some data files
Write some CUE code and JSON data (if you don’t already have some code that you want to update and use):
package example
// The data will be placed at this location.
input: {
name!: string
location: *"your part of the world" | string
}
output: """
Hello, \(input.name)!
How's the weather in \(input.location)?
"""
{
"name": "Charlie"
}
Check that the data file can be combined successfully with the CUE:
$ cue export . input.json --path input: -e output --out text
Hello, Charlie!
How's the weather in your part of the world?
Write some Go
Write a Go program that places the data in the input.json
file at a specific
location within its CUE evaluation
(or adapt your existing code to do the same):
package main
import (
"fmt"
"log"
"os"
"cuelang.org/go/cue"
"cuelang.org/go/cue/cuecontext"
"cuelang.org/go/cue/load"
"cuelang.org/go/encoding/json"
)
func main() {
ctx := cuecontext.New()
// Load the package in the current directory.
bis := load.Instances([]string{"."}, nil)
v := ctx.BuildInstance(bis[0])
// Load the input data.
jsonBytes, err := os.ReadFile("input.json")
if err != nil {
log.Fatal(err)
}
// Parse the input data to a CUE expression.
jsonData, err := json.Extract("input.json", jsonBytes)
if err != nil {
log.Fatal(err)
}
// Place the parsed data as the value of the "input" field.
complete := v.FillPath(cue.ParsePath("input"), jsonData)
// Extract the string value of the "output" field and print it.
output := complete.LookupPath(cue.ParsePath("output"))
msg, _ := output.String() // We know that "output" is a string type.
fmt.Printf("%v\n", msg)
}
Run the program
Add a dependency on cuelang.org/go
and ensure the Go module is tidy:
$ go get cuelang.org/go@v0.12.0-0.dev.0.20241121152206-5ed8701cee88
...
$ go mod tidy
...
Run the program,
printing the same multi-line string value that cue
produced earlier:
$ go run .
Hello, Charlie!
How's the weather in your part of the world?
Related content
- Concept Guide: How CUE works with Go
- All pages tagged with go api