openapi

package module
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 14, 2026 License: MIT Imports: 2 Imported by: 0

README ΒΆ

OpenAPI Generator for Go

Go Reference Go Report Card GitHub Sponsors

Generate OpenAPI 3.0.4 specifications from Go source code using swagger-style comments. Features an extensible parser system, multi-spec generation, incremental caching, and a powerful CLI.

✨ Features

  • πŸš€ OpenAPI 3.0.4 Compliant - Full support for the latest OpenAPI specification
  • πŸ“ Swagger-style Comments - Familiar swagger:meta, swagger:route, swagger:model directives
  • πŸ”Œ Extensible Parser System - Register custom parsers for new directives
  • πŸ“¦ Multi-Spec Generation - Generate multiple API specs from a single codebase
  • ⚑ Incremental Caching - Only re-process changed files
  • 🧹 Smart Schema Cleaning - Only include schemas used by each spec
  • 🎨 Swagger UI Integration - Download and serve Swagger UI with multi-spec support
  • πŸ› οΈ Powerful CLI - Easy-to-use command-line interface

πŸ“¦ Installation

go install github.com/kausys/openapi/cmd/openapi@latest

Or add to your project:

go get github.com/kausys/openapi

πŸš€ Quick Start

1. Add swagger comments to your code
// swagger:meta
// Title: My Awesome API
// Version: 1.0.0
// Description: A sample API to demonstrate OpenAPI generation
// License: MIT
type Meta struct{}

// swagger:route GET /users users listUsers
// Summary: List all users
// Description: Returns a list of all users in the system
// Security: bearerAuth
// Responses:
//   200: usersResponse

// swagger:model
type User struct {
    // The unique identifier
    // Example: 123
    ID   int    `json:"id"`
    // The user's full name
    // Example: John Doe
    Name string `json:"name"`
}
2. Generate the OpenAPI spec
openapi generate -o api.yaml
3. Output
openapi: "3.0.4"
info:
  title: My Awesome API
  version: 1.0.0
  description: A sample API to demonstrate OpenAPI generation
  license:
    name: MIT
paths:
  /users:
    get:
      operationId: listUsers
      summary: List all users
      tags:
        - users
      responses:
        "200":
          description: OK
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
          example: 123
        name:
          type: string
          example: John Doe

πŸ“– Documentation

Directives
Directive Description
swagger:meta API metadata (title, version, description, etc.)
swagger:route Operation definitions
swagger:model Schema/model definitions
swagger:parameters Parameter definitions
swagger:enum Enum definitions
swagger:allOf Schema composition
File Uploads (Multipart Form Data)

Support for file uploads using multipart/form-data:

// swagger:parameters uploadFile
type UploadFileParams struct {
    // in:body
    Body struct {
        // The file to upload
        // format: binary
        File string `json:"file"`
        // Optional file description
        Description string `json:"description"`
    }
}

// swagger:route POST /upload files uploadFile
// Consumes:
// - multipart/form-data
//
// Upload a file with metadata
func UploadFile() {}

This generates:

paths:
  /upload:
    post:
      operationId: uploadFile
      requestBody:
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                file:
                  type: string
                  format: binary
                description:
                  type: string
            encoding:
              file:
                contentType: application/octet-stream

Key points:

  • Use Consumes: directive with multipart/form-data
  • Mark file fields with format: binary
  • Mix file fields with regular form fields
  • Supports multiple file uploads in a single request
Multi-Spec Generation

Generate multiple API specs from a single codebase using the spec: directive:

// swagger:route GET /admin/users admin listAdminUsers
// spec: admin
type AdminListUsers struct{}

// swagger:route GET /users users listUsers
// spec: public mobile
type ListUsers struct{}
openapi generate --multi-specs -o ./specs/
# Generates: specs/admin.yaml, specs/public.yaml, specs/mobile.yaml
CLI Options
Usage:
  openapi generate [flags]

Flags:
  -o, --output string    Output file path (default "openapi.yaml")
  -f, --format string    Output format: yaml or json (default "yaml")
  -p, --pattern string   Package pattern to scan (default "./...")
  -d, --dir string       Root directory to scan (default ".")
      --no-cache         Disable incremental caching
      --multi-specs      Generate multiple specs based on spec: directives
      --spec string      Generate only a specific spec by name
      --clean-unused     Remove unreferenced schemas
      --validate         Validate the generated spec

🎨 Swagger UI Integration

The swagger package provides everything you need to serve Swagger UI with your OpenAPI specs.

Download Swagger UI

Use the CLI to download the latest Swagger UI release from GitHub:

# Check latest available version
openapi swagger version

# Download latest version with default customizations
openapi swagger download -o ./pkg/docs

# Download specific version
openapi swagger download -v 5.29.4 -o ./pkg/docs

# Download with simple single-spec initializer
openapi swagger download --simple -o ./pkg/docs

# Download without customizations
openapi swagger download --with-defaults=false -o ./pkg/docs

The download command automatically:

  • Fetches the latest release from GitHub API
  • Extracts only the dist/ folder
  • Removes source maps and ES module bundles
  • Injects custom initializer for multi-spec support
  • Adds custom CSS to hide Swagger branding
Serve Swagger UI in Your Application
package docs

import (
    _ "embed"
    "net/http"

    "github.com/kausys/openapi/swagger"
)

//go:embed swagger-ui.zip
var swaggerUIData []byte

//go:embed openapi.yaml
var specData []byte

func NewHandler() (*swagger.Handler, error) {
    return swagger.New(swaggerUIData, swagger.Config{
        BasePath:      "/swagger",      // Swagger UI served here
        SpecPath:      "/openapi/specs", // OpenAPI spec endpoint
        ResourcesPath: "/openapi/resources", // Multi-spec dropdown
        Specs: map[string][]byte{
            "api": specData,
        },
        DefaultSpec: "api",
    })
}
Framework Integration

Standard Library / Chi / Echo:

handler, _ := docs.NewHandler()
http.Handle("/swagger/", handler)
http.HandleFunc("/openapi/specs", handler.ServeHTTP)
http.HandleFunc("/openapi/resources", handler.ServeHTTP)

// Or register all routes at once:
mux := http.NewServeMux()
handler.Routes(mux)

Gin:

handler, _ := docs.NewHandler()
router := gin.Default()
router.Any("/swagger/*any", gin.WrapH(handler))
router.GET("/openapi/specs", gin.WrapH(handler))
router.GET("/openapi/resources", gin.WrapH(handler))

Fiber:

import "github.com/gofiber/adaptor/v2"

handler, _ := docs.NewHandler()
app := fiber.New()
app.Use("/swagger", adaptor.HTTPHandler(handler))
app.Get("/openapi/specs", adaptor.HTTPHandlerFunc(handler.ServeHTTP))
app.Get("/openapi/resources", adaptor.HTTPHandlerFunc(handler.ServeHTTP))
Multi-Spec Support

Serve multiple API specs with a dropdown selector:

handler, _ := swagger.New(swaggerUIData, swagger.Config{
    Specs: map[string][]byte{
        "public": publicSpecData,
        "admin":  adminSpecData,
        "mobile": mobileSpecData,
    },
    DefaultSpec: "public",
})

The Swagger UI will display a dropdown allowing users to switch between specs.

Configuration Options
Option Description Default
BasePath URL path for Swagger UI /swagger
SpecPath URL path for OpenAPI specs /openapi/specs
ResourcesPath URL path for spec list (multi-spec dropdown) /openapi/resources
Specs Map of spec name to YAML/JSON bytes required
DefaultSpec Default spec when no query param first spec
go:generate Integration

Add to your docs package for automatic spec generation:

//go:generate openapi generate -d ../.. -p ./... -o openapi.yaml --clean-unused
package docs

Then run:

go generate ./pkg/docs

πŸ”Œ Extensible Parser System

Register custom parsers to extend the functionality:

package main

import (
    "github.com/kausys/openapi/parser"
    _ "github.com/kausys/openapi/parser/tags" // Import built-in parsers
)

func init() {
    // Register a custom parser
    parser.Register(parser.DirectiveRoute, &MyCustomParser{})
}

πŸ’– Support the Project

If you find this project useful, please consider supporting its development:

πŸ“„ License

MIT License - see LICENSE for details.

πŸ™ Acknowledgments

Inspired by go-swagger with a modern, extensible architecture.

Documentation ΒΆ

Overview ΒΆ

Package openapi provides a Go library for generating OpenAPI 3.0.4 specifications from Go source code using swagger directives.

Quick Start ΒΆ

Generate an OpenAPI spec from your Go code:

spec, err := openapi.Generate(
	openapi.WithDir("."),
	openapi.WithPattern("./..."),
	openapi.WithOutput("openapi.yaml", "yaml"),
)

Directives ΒΆ

The library scans Go source code for the following directives:

  • swagger:meta - API metadata (title, version, description)
  • swagger:model - Schema definitions
  • swagger:route - Operation definitions
  • swagger:parameters - Parameter definitions
  • swagger:enum - Enum definitions

Caching ΒΆ

The library supports incremental builds through caching. By default, parsed schemas and routes are cached in a .openapi directory. Only files that have changed since the last build are re-parsed.

To disable caching:

spec, err := openapi.Generate(
	openapi.WithCache(false),
)

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

View Source
var WithCache = generator.WithCache

WithCache enables or disables incremental caching.

View Source
var WithCleanUnused = generator.WithCleanUnused

WithCleanUnused enables or disables removal of unreferenced schemas.

View Source
var WithDir = generator.WithDir

WithDir sets the root directory to scan from.

View Source
var WithFlatten = generator.WithFlatten

WithFlatten enables or disables schema flattening (inlining $refs).

View Source
var WithIgnorePaths = generator.WithIgnorePaths

WithIgnorePaths sets path patterns to exclude during scanning.

View Source
var WithOutput = generator.WithOutput

WithOutput sets the output file path and format ("yaml" or "json").

View Source
var WithPattern = generator.WithPattern

WithPattern sets the package pattern to scan (e.g., "./...", "./api/...").

View Source
var WithValidation = generator.WithValidation

WithValidation enables or disables spec validation after generation.

Functions ΒΆ

func Generate ΒΆ

func Generate(opts ...Option) (*spec.OpenAPI, error)

Generate creates an OpenAPI specification from Go source code. It scans the specified packages for swagger directives and generates a complete OpenAPI 3.0.4 specification.

Types ΒΆ

type Option ΒΆ

type Option = generator.Option

Option is a function type for configuring the generator.

Directories ΒΆ

Path Synopsis
Package cache provides incremental build caching for OpenAPI spec generation.
Package cache provides incremental build caching for OpenAPI spec generation.
cmd
openapi command
Package main provides the CLI entry point for the OpenAPI generator.
Package main provides the CLI entry point for the OpenAPI generator.
Package generator provides OpenAPI specification generation from Go source code.
Package generator provides OpenAPI specification generation from Go source code.
Package parser provides an extensible parsing system for swagger directives.
Package parser provides an extensible parsing system for swagger directives.
tags
Package tags provides built-in parsers for common swagger directives.
Package tags provides built-in parsers for common swagger directives.
Package scanner provides code scanning capabilities to extract OpenAPI information from Go source code using structured comments (directives).
Package scanner provides code scanning capabilities to extract OpenAPI information from Go source code using structured comments (directives).
Package swagger provides an HTTP handler to serve Swagger UI with embedded OpenAPI specs.
Package swagger provides an HTTP handler to serve Swagger UI with embedded OpenAPI specs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL