CUE -> OpenAPI generation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"encoding/json" | |
"fmt" | |
"log" | |
"cuelang.org/go/cue" | |
"cuelang.org/go/cue/load" | |
"cuelang.org/go/encoding/openapi" | |
) | |
func generateOpenAPI(defFile string, config *load.Config) ([]byte, error) { | |
buildInstances := load.Instances([]string{defFile}, config) | |
insts := cue.Build(buildInstances) | |
b, err := openapi.Gen(insts[0], nil) | |
if err != nil { | |
return nil, err | |
} | |
var out bytes.Buffer | |
err = json.Indent(&out, b, "", " ") | |
if err != nil { | |
return nil, err | |
} | |
return out.Bytes(), nil | |
} | |
func ExampleGenerateOpenAPI() { | |
src := bytes.NewBufferString(`#Identity: { | |
// first name of the person | |
first: =~ "[A-Z].*" | |
// Last name of the person | |
Last: =~ "[A-Z].*" | |
// Age of the person | |
Age?: number & < 130 | |
} | |
`) | |
b, err := generateOpenAPI("-", &load.Config{ | |
Stdin: src, | |
}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// This contains the OpenAPI.json definition | |
fmt.Println(string(b)) | |
// output: | |
// { | |
// "openapi": "3.0.0", | |
// "info": { | |
// "title": "Generated by cue.", | |
// "version": "no version" | |
// }, | |
// "paths": {}, | |
// "components": { | |
// "schemas": { | |
// "Identity": { | |
// "type": "object", | |
// "required": [ | |
// "first", | |
// "Last" | |
// ], | |
// "properties": { | |
// "first": { | |
// "description": "first name of the person", | |
// "type": "string", | |
// "pattern": "[A-Z].*" | |
// }, | |
// "Last": { | |
// "description": "Last name of the person", | |
// "type": "string", | |
// "pattern": "[A-Z].*" | |
// }, | |
// "Age": { | |
// "description": "Age of the person", | |
// "type": "number", | |
// "maximum": 130, | |
// "exclusiveMaximum": true | |
// } | |
// } | |
// } | |
// } | |
// } | |
// } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment