This first example shows how to load, build, and validate Cue.
simple.go
package main
import (
"fmt""cuelang.org/go/cue/cuecontext""cuelang.org/go/cue/load"
)
funcmain() {
// We need a cue.Context, the New'd return is ready to use
ctx := cuecontext.New()
// The entrypoints are the same as the files you'd specify at the command line
entrypoints := []string{"hello.cue"}
// Load Cue files into Cue build.Instances slice
// the second arg is a configuration object, we'll see this later
bis := load.Instances(entrypoints, nil)
// Loop over the instances, checking for errors and printing
for _, bi :=range bis {
// check for errors on the instance
// these are typically parsing errors
if bi.Err !=nil {
fmt.Println("Error during load:", bi.Err)
continue
}
// Use cue.Context to turn build.Instance to cue.Instance
value := ctx.BuildInstance(bi)
if value.Err() !=nil {
fmt.Println("Error during build:", value.Err())
continue
}
// print the error
fmt.Println("root value:", value)
// Validate the value
err := value.Validate()
if err !=nil {
fmt.Println("Error during validate:", err)
continue
}
}
}
hello.cue
packagehellohello: "world"#A: { foo: string}// to cause a load error, remove the '&'// to cause a build error, change '#A' to '#B'// to cause a validation error, change foo to '1'a: #A & { foo: "bar"}
go run fields.go
The Loading Configuration
Cue’s load.Instances has a second argument for configuring options.
The CLI, it uses the command, flags, and args to set these values.
When we load with Go, we can setup this Config object to modify the behavior.
The comments there explain how to use the various options.
Most are for advanced use cases and will make more sense
once you have seen more of Cue.
Others you have seen as flags to the CLI.