This tutorial demonstrates how to get started with CUE’s Go API, and write a Go program to load and evaluate some CUE.
Prerequisites
- A tool to edit text files. Any text editor you have will be fine, for example VSCode.
- A command terminal.
cue
works on all platforms, so any terminal on Linux or macOS, and on PowerShell,cmd.exe
or WSL in Windows. - An installed
go
binary (installation details) - An installed
cue
binary (installation details) - Some awareness of CUE schemata (Constraints and Definitions in the CUE tour)
This tutorial is written using the following versions of go
and cue
:
TERMINAL
$ cue version
cue version v0.12.0-alpha.1.0.20241224145825-c905888d9323
...
$ go version
go version go1.23.2 linux/amd64
Create a CUE module
1
Initialize a CUE module to hold our configuration:
TERMINAL
$ cue mod init company.example/configuration
2
Write some CUE code:
some.cue
package example
output: "Hello \(name)"
name: "Joe"
3
Verify that the configuration successfully evaluates:
TERMINAL
$ cue export
{
"output": "Hello Joe",
"name": "Joe"
}
Create a Go module and program
4
Initialize a Go module to contain your program:
TERMINAL
$ go mod init company.example/configuration
...
5
Write a Go program to load the CUE and print a message based on the output
field:
main.go
package main
import (
"fmt"
"log"
"cuelang.org/go/cue"
"cuelang.org/go/cue/cuecontext"
"cuelang.org/go/cue/load"
)
func main() {
ctx := cuecontext.New()
// Load the package "example" from the current directory.
// We don't need to specify a config in this example.
insts := load.Instances([]string{"."}, nil)
// The current directory just has one file without any build tags,
// and that file belongs to the example package.
// So we get a single instance as a result.
v := ctx.BuildInstance(insts[0])
if err := v.Err(); err != nil {
log.Fatal(err)
}
// Lookup the 'output' field and print it out
output := v.LookupPath(cue.ParsePath("output"))
fmt.Println(output)
}
6
Add a dependency on cuelang.org/go
and ensure the Go module is tidy:
TERMINAL
$ go get cuelang.org/go@v0.12.0-alpha.1.0.20241224145825-c905888d9323
...
$ go mod tidy
...
You can use @latest
in place of a specified version.
Run the Go program
7
Run the Go program:
TERMINAL
$ go run .
"Hello Joe"
Congratulations!
Well done - you’ve successfully written your first Go program to load and evaluate CUE.