| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
OpenAPI v3 Code Generator for Go.
go install -v github.com/ogen-go/ogen/cmd/ogen@latest//go:generate go run github.com/ogen-go/ogen/cmd/ogen --target target/dir -package api --clean schema.jsonor using container:
docker run --rm \
--volume ".:/workspace" \
ghcr.io/ogen-go/ogen:latest --target workspace/petstore --clean workspace/petstore.ymlExample generated structure from schema:
// Pet describes #/components/schemas/Pet.
type Pet struct {
Birthday time.Time `json:"birthday"`
Friends []Pet `json:"friends"`
ID int64 `json:"id"`
IP net.IP `json:"ip"`
IPV4 net.IP `json:"ip_v4"`
IPV6 net.IP `json:"ip_v6"`
Kind PetKind `json:"kind"`
Name string `json:"name"`
Next OptData `json:"next"`
Nickname NilString `json:"nickname"`
NullStr OptNilString `json:"nullStr"`
Rate time.Duration `json:"rate"`
Tag OptUUID `json:"tag"`
TestArray1 [][]string `json:"testArray1"`
TestDate OptTime `json:"testDate"`
TestDateTime OptTime `json:"testDateTime"`
TestDuration OptDuration `json:"testDuration"`
TestFloat1 OptFloat64 `json:"testFloat1"`
TestInteger1 OptInt `json:"testInteger1"`
TestTime OptTime `json:"testTime"`
Type OptPetType `json:"type"`
URI url.URL `json:"uri"`
UniqueID uuid.UUID `json:"unique_id"`
}Example generated server interface:
// Server handles operations described by OpenAPI v3 specification.
type Server interface {
PetGetByName(ctx context.Context, params PetGetByNameParams) (Pet, error)
// ...
}Example generated client method signature:
type PetGetByNameParams struct {
Name string
}
// GET /pet/{name}
func (c *Client) PetGetByName(ctx context.Context, params PetGetByNameParams) (res Pet, err error)Instead of using pointers, ogen generates generic wrappers.
For example, OptNilString is string that is optional (no value) and can be null.
// OptNilString is optional nullable string.
type OptNilString struct {
Value string
Set bool
Null bool
}Multiple convenience helper methods and functions are generated, some of them:
func (OptNilString) Get() (v string, ok bool)
func (OptNilString) IsNull() bool
func (OptNilString) IsSet() bool
func NewOptNilString(v string) OptNilStringIf ogen encounters recursive types that can't be expressed in go, pointers are used as fallback.
For oneOf sum-types are generated. ID that is one of [string, integer] will be represented like that:
type ID struct {
Type IDType
String string
Int int
}
// Also, some helpers:
func NewStringID(v string) ID
func NewIntID(v int) IDogen automatically infers how to discriminate between oneOf variants using several strategies:
1. Type-based discrimination (for primitive types)
Variants with different JSON types are discriminated by checking the JSON type at runtime:
{
"oneOf": [
{"type": "string"},
{"type": "integer"}
]
}2. Explicit discriminator (when discriminator field is specified)
When a discriminator field is defined in the schema, ogen uses it directly:
{
"oneOf": [...],
"discriminator": {
"propertyName": "type",
"mapping": {"user": "#/components/schemas/User", ...}
}
}3. Field-based discrimination (automatic inference from unique fields)
ogen analyzes the fields in each variant to find discriminating characteristics:
{
"oneOf": [
{"type": "object", "required": ["userId"], "properties": {"userId": {"type": "string"}}},
{"type": "object", "required": ["orderId"], "properties": {"orderId": {"type": "string"}}}
]
}{
"oneOf": [
{
"type": "object",
"required": ["id", "value"],
"properties": {
"id": {"type": "string"},
"value": {"type": "string"}
}
},
{
"type": "object",
"required": ["id", "value"],
"properties": {
"id": {"type": "integer"},
"value": {"type": "number"}
}
}
]
}In this case, ogen checks the JSON type of the id field at runtime to determine which variant to decode.
{
"oneOf": [
{
"type": "object",
"required": ["status"],
"properties": {
"status": {"type": "string", "enum": ["active", "pending"]}
}
},
{
"type": "object",
"required": ["status"],
"properties": {
"status": {"type": "string", "enum": ["inactive", "deleted"]}
}
}
]
}In this case, ogen checks the actual string value of the status field at runtime and matches it against each variant's enum values. The enum values must be disjoint (non-overlapping) for this to work. If enum values overlap, ogen will report an error and suggest using an explicit discriminator.
ogen supports the JSON Schema const keyword, which specifies that a field must have a fixed value (introduced in JSON Schema draft 6 and supported in OpenAPI 3.0+). When a field has a const value, it is encoded directly in the generated JSON encoder without requiring the struct field to be set.
components:
schemas:
ErrorResponse:
type: object
properties:
code:
type: integer
const: 400
status:
type: string
const: "error"
message:
type: stringThe generated struct includes the field, but the encoder hardcodes the const value:
type ErrorResponse struct {
Code int64 `json:"code"` // const: 400
Status string `json:"status"` // const: "error"
Message string `json:"message"`
}
func (s *ErrorResponse) encodeFields(e *jx.Encoder) {
{
e.FieldStart("code")
e.Int64(400) // Const value encoded directly
}
{
e.FieldStart("status")
e.Str("error") // Const value encoded directly
}
{
e.FieldStart("message")
e.Str(s.Message) // Regular field
}
}OpenAPI enables Specification Extensions, which are implemented as patterned fields that are always prefixed by x-.
Optionally, server name can be specified by x-ogen-server-name, for example:
{
"openapi": "3.0.3",
"servers": [
{
"x-ogen-server-name": "production",
"url": "https://{region}.example.com/{val}/v1",
},
{
"x-ogen-server-name": "prefix",
"url": "/{val}/v1",
},
{
"x-ogen-server-name": "const",
"url": "https://cdn.example.com/v1"
}
],
(...)Optionally, type name can be specified by x-ogen-name, for example:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"x-ogen-name": "Name",
"properties": {
"foobar": {
"$ref": "#/$defs/FooBar"
}
},
"$defs": {
"FooBar": {
"x-ogen-name": "FooBar",
"type": "object",
"properties": {
"foo": {
"type": "string"
}
}
}
}
}Optionally, type name can be specified by x-ogen-properties, for example:
components:
schemas:
Node:
type: object
properties:
parent:
$ref: "#/components/schemas/Node"
child:
$ref: "#/components/schemas/Node"
x-ogen-properties:
parent:
name: "Prev"
child:
name: "Next"The generated source code looks like:
// Ref: #/components/schemas/Node
type Node struct {
Prev *Node `json:"parent"`
Next *Node `json:"child"`
}Optionally, additional Go struct field tags can be specified by x-oapi-codegen-extra-tags, for example:
components:
schemas:
Pet:
type: object
required:
- id
properties:
id:
type: integer
format: int64
x-oapi-codegen-extra-tags:
gorm: primaryKey
valid: customIdValidatorThe generated source code looks like:
// Ref: #/components/schemas/Pet
type Pet struct {
ID int64 `gorm:"primaryKey" valid:"customNameValidator" json:"id"`
}By default, ogen loads the entire JSON body into memory before decoding it. Optionally, streaming JSON encoding can be enabled by x-ogen-json-streaming, for example:
requestBody:
required: true
content:
application/json:
x-ogen-json-streaming: true
schema:
type: array
items:
type: numberOptionally, custom validation can be specified by x-ogen-validate, for example:
components:
schemas:
Product:
type: object
properties:
name:
type: string
x-ogen-validate:
minWords: 2
tags:
type: array
items:
type: string
x-ogen-validate:
uniqueItems: true
metadata:
type: object
additionalProperties: true
x-ogen-validate:
fieldCount:
min: 1
max: 10Custom validators must be registered before validation is performed:
import "github.com/ogen-go/ogen/validate"
// Register validators
validate.RegisterValidator("minWords", func(value any, params any) error {
// ... validate minimum word count
})
validate.RegisterValidator("uniqueItems", func(value any, params any) error {
// ... validate array has no duplicate items
})
validate.RegisterValidator("fieldCount", func(value any, params any) error {
// ... validate object field count within min/max range
})Optionally, operations can be grouped so a handler interface will be generated for each group of operations. This is useful for organizing operations for large APIs.
The group for operations on a path or individual operations can be specified by x-ogen-operation-group, for example:
paths:
/images:
x-ogen-operation-group: Images
get:
operationId: listImages
...
/images/{imageID}:
x-ogen-operation-group: Images
get:
operationId: getImageByID
...
/users:
x-ogen-operation-group: Users
get:
operationId: listUsers
...The generated handler interfaces look like this:
// x-ogen-operation-group: Images
type ImagesHandler interface {
ListImages(ctx context.Context, req *ListImagesRequest) (*ListImagesResponse, error)
GetImageByID(ctx context.Context, req *GetImagesByIDRequest) (*GetImagesByIDResponse, error)
}
// x-ogen-operation-group: Users
type UsersHandler interface {
ListUsers(ctx context.Context, req *ListUsersRequest) (*ListUsersResponse, error)
}
type Handler interface {
ImagesHandler
UsersHandler
// All un-grouped operations will be on this interface
}Code generation provides very efficient and flexible encoding and decoding of json:
// Decode decodes Error from json.
func (s *Error) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode Error to nil")
}
return d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "code":
if err := func() error {
v, err := d.Int64()
s.Code = int64(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"code\"")
}
case "message":
if err := func() error {
v, err := d.Str()
s.Message = string(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"message\"")
}
default:
return d.Skip()
}
return nil
})
}| Back | FazBrowse Home | New Git URL |