Categorygithub.com/ogen-go/ogen
modulepackage
1.3.0
Repository: https://github.com/ogen-go/ogen.git
Documentation: pkg.go.dev

# README

ogen svg logo

ogen Go Reference codecov stable

OpenAPI v3 Code Generator for Go.

Install

go get -d github.com/ogen-go/ogen

Usage

//go:generate go run github.com/ogen-go/ogen/cmd/ogen --target target/dir -package api --clean schema.json

or using container:

docker run --rm \
  --volume ".:/workspace" \
  ghcr.io/ogen-go/ogen:latest --target workspace/petstore --clean workspace/petstore.yml

Features

  • No reflection or interface{}
    • The json encoding is code-generated, optimized and uses go-faster/jx for speed and overcoming encoding/json limitations
    • Validation is code-generated according to spec
  • Code-generated static radix router
  • No more boilerplate
    • Structures are generated from OpenAPI v3 specification
    • Arguments, headers, url queries are parsed according to specification into structures
    • String formats like uuid, date, date-time, uri are represented by go types directly
  • Statically typed client and server
  • Convenient support for optional, nullable and optional nullable fields
    • No more pointers
    • Generated Optional[T], Nullable[T] or OptionalNullable[T] wrappers with helpers
    • Special case for array handling with nil semantics relevant to specification
      • When array is optional, nil denotes absence of value
      • When nullable, nil denotes that value is nil
      • When required, nil currently the same as [], but is actually invalid
      • If both nullable and required, wrapper will be generated (TODO)
  • Generated sum types for oneOf
    • Primitive types (string, number) are detected by type
    • Discriminator field is used if defined in schema
    • Type is inferred by unique fields if possible
  • Extra Go struct field tags in the generated types
  • OpenTelemetry tracing and metrics

Example 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)

Generics

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) OptNilString

Recursive types

If ogen encounters recursive types that can't be expressed in go, pointers are used as fallback.

Sum types

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) ID

Extension properties

OpenAPI enables Specification Extensions, which are implemented as patterned fields that are always prefixed by x-.

Server name

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"
    }
  ],
(...)

Custom type name

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"
        }
      }
    }
  }
}

Custom field name

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"`
}

Extra struct field tags

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: customIdValidator

The generated source code looks like:

// Ref: #/components/schemas/Pet
type Pet struct {
    ID   int64     `gorm:"primaryKey" valid:"customNameValidator" json:"id"`
}

Streaming JSON encoding

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: number

Operation groups

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
}

JSON

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
	})
}

Links

# Packages

No description provided by the author
Package conv contains helper functions for converting between various data types.
Package gen contains the code generator for OpenAPI Spec.
Package http implements crazy ideas for http optimizations that should be mostly std compatible.
Package json contains helper functions for encoding and decoding JSON.
Package jsonpointer contains RFC 6901 JSON Pointer implementation.
Package jsonschema contains parser for JSON Schema.
Package location provides utilities to track values over the spec.
Package middleware provides a middleware interface for ogen.
Package ogenerrors contains ogen errors type definitions and helpers.
Package ogenregex provides an interface to the regex engine.
Package openapi represents OpenAPI v3 Specification in Go.
Package otelogen provides OpenTelemetry tracing for ogen.
No description provided by the author
Package uri implements OpenAPI path/query parameter encoding.
Package validate contains validation helpers.

# Functions

Binary returns a sequence of octets OAS data type (Schema).
Bool returns a boolean OAS data type (Schema).
Bytes returns a base64 encoded OAS data type (Schema).
Date returns a date as defined by full-date - RFC3339 OAS data type (Schema).
DateTime returns a date as defined by date-time - RFC3339 OAS data type (Schema).
Double returns a double OAS data type (Schema).
Float returns a float OAS data type (Schema).
Int returns an integer OAS data type (Schema).
Int32 returns an 32-bit integer OAS data type (Schema).
Int64 returns an 64-bit integer OAS data type (Schema).
NewContact returns a new Contact.
NewInfo returns a new Info.
NewLicense returns a new License.
NewNamedParameter returns a new NamedParameter.
NewNamedPathItem returns a new NamedPathItem.
NewNamedRequestBody returns a new NamedRequestBody.
NewNamedResponse returns a new NamedResponse.
NewNamedSchema returns a new NamedSchema.
NewOperation returns a new Operation.
NewParameter returns a new Parameter.
NewPathItem returns a new PathItem.
NewProperty returns a new Property.
NewRequestBody returns a new RequestBody.
NewResponse returns a new Response.
NewSchema returns a new Schema.
NewServer returns a new Server.
NewSpec returns a new Spec.
Parse parses JSON/YAML into OpenAPI Spec.
Password returns an obscured OAS data type (Schema).
String returns a string OAS data type (Schema).
UUID returns a UUID OAS data type (Schema).

# Structs

AdditionalProperties is JSON Schema additionalProperties validator description.
Components Holds a set of reusable objects for different aspects of the OAS.
Contact information for the exposed API.
Discriminator discriminates types for OneOf, AllOf, AnyOf.
Encoding describes single encoding definition applied to a single schema property.
Example object.
ExternalDocumentation describes a reference to external resource for extended documentation.
Info provides metadata about the API.
Items is unparsed JSON Schema items validator description.
License information for the exposed API.
Link describes a possible design-time link for a response.
Media provides schema and examples for the media type identified by its key.
NamedParameter can be used to construct a reference to the wrapped Parameter.
NamedPathItem can be used to construct a reference to the wrapped PathItem.
NamedRequestBody can be used to construct a reference to the wrapped RequestBody.
NamedResponse can be used to construct a reference to the wrapped Response.
NamedSchema can be used to construct a reference to the wrapped Schema.
OAuthFlow is configuration details for a supported OAuth Flow.
OAuthFlows allows configuration of the supported OAuth Flows.
Operation describes a single API operation on a path.
Parameter describes a single operation parameter.
PathItem Describes the operations available on a single path.
PatternProperty is item of PatternProperties.
Property is item of Properties.
RequestBody describes a single request body.
Response describes a single response from an API Operation, including design-time, static links to operations based on the response.
The Schema Object allows the definition of input and output data types.
SecurityScheme defines a security scheme that can be used by the operations.
Server represents a Server.
ServerVariable describes an object representing a Server Variable for server URL template substitution.
Spec is the root document object of the OpenAPI document.
Tag adds metadata to a single tag that is used by the Operation Object.
XML is a metadata object that allows for more fine-tuned XML model definitions.

# Type aliases

Callback is a map of possible out-of band callbacks related to the parent operation.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Header describes header response.
No description provided by the author
No description provided by the author
No description provided by the author
Paths holds the relative paths to the individual endpoints and their operations.
PatternProperties is unparsed JSON Schema patternProperties validator description.
Properties is unparsed JSON Schema properties validator description.
No description provided by the author
Responses is a container for the expected responses of an operation.
No description provided by the author
No description provided by the author