Working with CUE from Go starts with cue.Context.
Code is compiled and values are built using a context.
You will see the basic methods for cue.Context here
and later pages will increase the sophistication.
When working with multiple values, they should come from the same runtime.
This requirement will be removed in a future version.
Compiling with Context
This is the simplest program to print a CUE value.
It will print the first error message if you have one.
context.go
packagemainimport("fmt""cuelang.org/go/cue""cuelang.org/go/cue/cuecontext")constval=`
i: int
s: "hello"
`funcmain(){var(c*cue.Contextvcue.Value)// create a contextc=cuecontext.New()// compile some CUE into a Valuev=c.CompileString(val)// print the valuefmt.Println(v)}
go run context.go
{ i: int s: "hello"}
Compiling with a Scope
If you have schemas in one string and values in another,
you can use the cue.Scope option to provide a “context” for the cue.Context.
scope.go
packagemainimport("fmt""cuelang.org/go/cue""cuelang.org/go/cue/cuecontext")constschema=`
#schema: {
i: int
s: string
}
`constval=`
v: #schema & {
i: 1
s: "hello"
}
`funcmain(){var(c*cue.Contextscue.Valuevcue.Value)// create a contextc=cuecontext.New()// compile our schema firsts=c.CompileString(schema)// compile our value with scopev=c.CompileString(val,cue.Scope(s))// print the valuefmt.Println(v)}
go run scope.go
{ v: { i: 1 s: "hello" }}
Encoding Values from Go
You can also transform your Go types and values into CUE values.
We can control the output with struct tags. Note that
Only public members will be encoded by CUE.
We can use omitempty to prevent output, but this impacts the type encoding as well.
Numerical types have some quirks we’ll talk about later. CUE normally uses math/big types.
packagemainimport("fmt""cuelang.org/go/cue""cuelang.org/go/cue/cuecontext")typeValstruct{Iint`json:"i"`Sstring`json:"s,omitempty"`bbool}funcmain(){var(c*cue.Contextvcue.Value)val:=Val{I:1,S:"hello",b:true,}// create a contextc=cuecontext.New()// compile some CUE into a Valuev=c.Encode(val)// print the valuefmt.Println(v)// we can also encode typest:=c.EncodeType(Val{})fmt.Println(t)}