Awesome Go

oapixconstgen

CategoryGo Generate Tools
SubcategoryGo Generate Tools
Stars0

Generate typed Go constants from an OpenAPI spec's x-constants extension

About oapixconstgen

oapixconstgen

CI coverage version license

A Go tool that extracts typed constants from OpenAPI specification files and generates Go code.

Overview

When defining OpenAPI specs, you often need to reuse constant values (like pagination limits, timeouts, or configuration values) across multiple places using YAML anchors. oapixconstgen reads these constants from the x-constants extension and generates a Go file with properly typed constants, keeping your API spec and Go code in sync.

Installation

go install github.com/psyb0t/oapixconstgen@latest

Or add as a project tool (Go 1.24+):

go get -tool github.com/psyb0t/oapixconstgen@latest

This adds it to your go.mod under the tool directive, making it a versioned project dependency.

Usage

Given an OpenAPI spec with x-constants:

openapi: "3.0.0"

x-constants:
  int:
    defaultPageSize: &defaultPageSize 20
    maxPageSize: &maxPageSize 100
  string:
    defaultLocale: &defaultLocale "en-US"

paths:
  /items:
    get:
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
            default: *defaultPageSize
            maximum: *maxPageSize

Run the generator:

oapixconstgen -spec=api.yaml -out=./internal/api -pkg=api

This generates internal/api/constants.gen.go:

// Code generated by oapixconstgen. DO NOT EDIT.

package api

const (
	DefaultLocale   string = "en-US"
	DefaultPageSize int    = 20
	MaxPageSize     int    = 100
)

The flags are -spec (required), -out (default .), -file (default constants.gen.go) and -pkg (default api). The type keys are the Go integer, float, string and bool types, and names like max_page_size become MaxPageSize. The documentation has the details, including go generate setup and what makes a run fail.

Documentation

The full docs live at psyb0t.github.io/oapixconstgen.

PageWhat's in it
Command lineEvery flag, exit codes, log lines, and go generate setup
The x-constants blockThe 14 type keys, how values and names are written, ordering, what fails
DevelopmentMake targets, coverage gate, CI and releases

Sponsor

License

MIT

Frequently Asked Questions

What is oapixconstgen?

oapixconstgen is a Go Generate Tools library for the Go programming language. Generate typed Go constants from an OpenAPI spec's x-constants extension

How do I install oapixconstgen?

Install oapixconstgen with the Go module system using `go get psyb0t/oapixconstgen`. Check the repository for the current installation instructions.

What category does oapixconstgen belong to?

oapixconstgen is listed under Go Generate Tools, specifically Go Generate Tools.

← Back to Go Generate Tools