specgen

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2025 License: MIT Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-specgen

🚀 Generate OpenAPI (Swagger) specifications from Go structs with ease

Go Reference Go Version

go-specgen is a Go library for generating OpenAPI 3.0 specifications from your Go structs. Built on top of swaggest/openapi-go, it provides a clean API to define your routes and automatically generate comprehensive API documentation.

📦 Installation

go get github.com/lutfiandri/go-specgen

🎯 Quick Start

Here's a simple example with two endpoints:

package main

import (
	"log"
	"github.com/lutfiandri/go-specgen"
)

// Request types
type CreateUserRequest struct {
	Name  string `json:"name" required:"true"`
	Email string `json:"email" required:"true" format:"email"`
}

type UserResponse struct {
	ID    int    `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
}

type ErrorResponse struct {
	Message string `json:"message"`
	Code    string `json:"code"`
}

func main() {
	// Configure the OpenAPI spec
	title := "User API"
	description := "A simple user management API"
	version := "1.0.0"

	config := specgen.SpecConfig{
		Title:                   &title,
		Description:             &description,
		Version:                 &version,
		WithBearerTokenSecurity: true,
	}

	// Define your routes
	routes := []specgen.Route{
		{
			Path:   "/users",
			Method: "GET",
			Request: struct{}{},
			Responses: []specgen.RouteResponse{
				{
					StatusCode: 200,
					Response:   []UserResponse{},
				},
			},
		},
		{
			Path:   "/users",
			Method: "POST",
			Request: CreateUserRequest{},
			Responses: []specgen.RouteResponse{
				{
					StatusCode: 201,
					Response: UserResponse{},
				},
				{
					StatusCode: 400,
					Response: ErrorResponse{}
				},
			},
		},
	}

	// Generate the OpenAPI spec
	if err := specgen.GenerateOpenAPISpec(config, "openapi.yaml", routes); err != nil {
		log.Fatalf("Failed to generate OpenAPI spec: %v", err)
	}

	log.Println("✅ OpenAPI specification generated successfully!")
}

Run it:

go run main.go

This will generate an openapi.yaml file with your API specification!

📚 More Examples

Check out the example directory for a complete CRUD API example with multiple endpoints, error handling, and path parameters.

🛠️ Usage

SpecConfig

Configure your OpenAPI specification:

config := specgen.SpecConfig{
	Title:                   stringPtr("My API"),
	Description:             stringPtr("API description"),
	Version:                 stringPtr("1.0.0"),
	WithBearerTokenSecurity: true, // Optional: enable Bearer token auth
}
Defining Routes

Each route requires:

  • Path - The endpoint path (e.g., /users/{id})
  • Method - HTTP method (GET, POST, PUT, DELETE, etc.)
  • Request - Request body/params struct
  • Responses - Array of possible responses with status codes
route := specgen.Route{
	Tags:        []string{"users"},
	Summary:     "Create user",
	Description: "Create a new user",
	Path:        "/users",
	Method:      "POST",
	Request:     CreateUserRequest{},
	Responses: []specgen.RouteResponse{
		{StatusCode: 201, Response: UserResponse{}},
		{StatusCode: 400, Response: ErrorResponse{}},
	},
}

✅ Validation

go-specgen supports parsing validation tags from the validate struct tag, following the go-playground/validator v10 format. These validators are automatically converted to OpenAPI schema constraints.

Example
type CreateUserRequest struct {
	Name     string   `json:"name" validate:"required,min=3,max=50"`
	Email    string   `json:"email" validate:"required,email"`
	Age      int      `json:"age" validate:"required,min=18,max=120"`
	Score    float64  `json:"score" validate:"gte=0,lte=100"`
	Gender   string   `json:"gender" validate:"required,oneof=male female"`
	Tags     []string `json:"tags" validate:"min=1,max=10"`
	Password string   `json:"password" validate:"required,len=8"`
}

For a complete reference of all supported validator tags, see VALIDATOR.md.

🗺️ Roadmap

  • Generate OpenAPI in YAML
  • Generate OpenAPI in JSON
  • Parse request struct that using github.com/go-playground/validator
  • Support for query parameters and path parameters parsing
  • Trim and prefix request/response schema names
  • Support for request headers

🙏 Acknowledgments

Built with swaggest/openapi-go - a powerful OpenAPI 3.0 reflection library for Go.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateOpenAPISpec

func GenerateOpenAPISpec(config SpecConfig, outputFile string, routes []Route) error

func ParseValidatorV10 added in v0.2.0

func ParseValidatorV10(reflector *openapi3.Reflector, structure any)

Types

type Route

type Route struct {
	Tags        []string
	Summary     string
	Description string
	Path        string
	Method      string
	Request     any
	Responses   []RouteResponse
}

type RouteResponse

type RouteResponse struct {
	StatusCode int
	Response   any
}

type SpecConfig

type SpecConfig struct {
	Title                   *string
	Description             *string
	Version                 *string
	WithBearerTokenSecurity bool
}

type StructTags added in v0.2.0

type StructTags struct {
	Name string
	Tags []Tag
}

func ExtractStructTags added in v0.2.0

func ExtractStructTags(structure any, tagKeys []string) []StructTags

type Tag added in v0.2.0

type Tag struct {
	Key   string
	Value string
}

func ExtractStructFieldTags added in v0.2.0

func ExtractStructFieldTags(field reflect.StructField, tagKeys []string) []Tag

type ValidationInfo added in v0.2.0

type ValidationInfo struct {
	Required bool
	Format   string // email, uri, uuid, date-time
	OneOf    []string
	Min      *float64
	Max      *float64
	Len      *int64
	Gt       *float64
	Lt       *float64
	Gte      *float64
	Lte      *float64
}

func ParseValidatorV10Tag added in v0.2.0

func ParseValidatorV10Tag(validateTag string) ValidationInfo

Directories

Path Synopsis
example
basic command
with_validator command

Jump to

Keyboard shortcuts

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