Home

cuesonnet @ad92adf766ccabb211e2344123f01dcf37636f22 - refs - log -
-
https://git.jolheiser.com/cuesonnet.git
CUE + Jsonnet
drwxrwxrwx
36 B
cmd/
drwxrwxrwx
491 B
testdata/
-rw-r--r--
1.1 kB
LICENSE
-rw-r--r--
1.8 kB
README.md
-rw-r--r--
1.5 kB
cuesonnet.go
-rw-r--r--
18 kB
cuesonnet_decode_test.go
-rw-r--r--
9.4 kB
cuesonnet_test.go
-rw-r--r--
782 B
go.mod
-rw-r--r--
5.6 kB
go.sum

cuesonnet

Validate Jsonnet data against CUE constraints.

Usage

Example Schema

import "time"

#Schema: {
	// Basic schema
	firstName: string
	lastName:  string
	age:       int
	birthday:  string

	// Refine as needed
	#Title:    =~"^[A-Z]" | error("must start with an uppercase letter")
	firstName: #Title
	lastName:  #Title
	age:       >0
	birthday:  time.Format("01/02/2006")

	// Defaults
	gopher: bool | *true
}

// Apply the schema to root
#Schema

Example Jsonnet

{
  firstName: 'Jim',
  lastName: 'Jimbly',
  age: 45,
  birthday: '01/02/2003',
}

Embedding the schema is the recommended pattern:

//go:embed schema.cue
var schema cuesonnet.Schema

var result MyStruct
if err := schema.Decode(r, &result); err != nil {
    // handle validation errors
}

Schema notes

Human-readable errors: CUE constraint errors surface raw expressions by default (e.g. out of bound =~"..."). Use | error("message") in your schema to replace them with plain language - see #Title in the example above.

float vs number: JSON has one number type. go-jsonnet serializes 50.0 as 50, which CUE treats as int and rejects against float. Use number for fields that should accept whole-number values; reserve float only when integers must be rejected.

Tests

testdata/ contains a large list of schemas and Jsonnet fixtures covering CUE features (types, constraints, structs, lists, disjunctions, defaults, definitions, composition, stdlib) and Jsonnet features (functions, comprehensions, conditionals, inheritance, multiline strings, self-reference, stdlib). See cuesonnet_test.go and cuesonnet_decode_test.go.

License

MIT