Skip to content

Repository files navigation

Swagger to Go Structs Generator

A CLI tool that parses Swagger/OpenAPI YAML files and generates Go request and response structs.

Features

  • Parses OpenAPI 3.x and Swagger 2.x YAML files
  • Generates properly formatted Go structs with JSON tags
  • Intelligent base struct extraction - Automatically identifies common field patterns across structs and extracts them into reusable base structs
  • Supports nested objects and arrays
  • Handles various data types (string, integer, number, boolean, arrays, objects)
  • Automatic PascalCase conversion for struct and field names
  • Supports time.Time for date/date-time formats
  • Generates separate files for each struct
  • Configurable package name and output directory
  • Uses Go struct embedding for cleaner, more maintainable code

Installation

Build from Source

go build -o swagger-gen ./cmd/swagger-gen

Usage

Basic Usage

./swagger-gen -input <path-to-swagger.yaml> -output <output-directory> -package <package-name>

Command-line Flags

  • -input (required): Path to the Swagger/OpenAPI YAML file
  • -output (optional): Output directory for generated structs (default: ./generated)
  • -package (optional): Package name for generated structs (default: models)

Examples

Generate structs from Quote.yaml:

./swagger-gen -input Quote.yaml -output ./generated/quote -package models

Generate structs with default output directory:

./swagger-gen -input approval.yml -package api

Generated Output

The tool generates:

  1. One Go file per struct
  2. Struct names derived from paths and operation IDs
  3. JSON tags for all fields
  4. Proper Go types for OpenAPI types
  5. omitempty tags for optional fields
  6. Base structs for common field patterns (when 3+ structs share fields)

Example Generated Struct

package models

import "time"

type QuoteCalculateRequest struct {
    AgeProofType string    `json:"age_proof_type,omitempty"`
    CeasingAge   int       `json:"ceasing_age"`
    DateOfBirth  time.Time `json:"date_Of_birth"`
    Frequency    string    `json:"frequency"`
    Gender       string    `json:"gender"`
    ProductId    int       `json:"product_id"`
    SumAssured   float64   `json:"sum_assured"`
}

Base Struct Extraction

When multiple structs (3 or more) share common fields, the tool automatically extracts those fields into a base struct and uses Go's struct embedding to reduce code duplication.

Example - Before optimization:

type Response400 struct {
    ErrorCode string `json:"errorCode,omitempty"`
    Message   string `json:"message,omitempty"`
}

type Response404 struct {
    ErrorCode string `json:"errorCode,omitempty"`
    Message   string `json:"message,omitempty"`
    Details   []interface{} `json:"details,omitempty"`
}

type Response500 struct {
    ErrorCode   string `json:"errorCode,omitempty"`
    Message     string `json:"message,omitempty"`
    ReferenceId string `json:"referenceId,omitempty"`
}

After optimization (actual generated code):

// Base struct with common fields
type BaseErrorCodeMessage struct {
    ErrorCode string `json:"errorCode,omitempty"`
    Message   string `json:"message,omitempty"`
}

// Structs using embedding
type Response400 struct {
    BaseErrorCodeMessage
}

type Response404 struct {
    BaseErrorCodeMessage

    Details []interface{} `json:"details,omitempty"`
}

type Response500 struct {
    BaseErrorCodeMessage

    ReferenceId string `json:"referenceId,omitempty"`
}

This approach:

  • Reduces code duplication
  • Makes common fields easier to maintain
  • Follows Go best practices for composition
  • Maintains full JSON marshaling/unmarshaling compatibility

Type Mapping

OpenAPI Type Go Type
string string
string (date) time.Time
string (date-time) time.Time
integer int
integer (int64) int64
number float64
number (float) float32
boolean bool
array []T
object map[string]T or interface{}

Project Structure

.
├── cmd/
│   └── swagger-gen/
│       └── main.go          # CLI entry point
├── pkg/
│   ├── parser/
│   │   └── parser.go        # Swagger YAML parser
│   ├── generator/
│   │   └── generator.go     # Struct generator
│   └── writer/
│       └── writer.go        # File writer
├── generated/               # Output directory (created on first run)
├── go.mod
└── README.md

Dependencies

License

MIT

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages