ginopenapi

package module
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2025 License: MIT Imports: 9 Imported by: 0

README

ginopenapi

Go Reference

A lightweight adapter for the Gin web framework that automatically generates OpenAPI 3.x specifications from your routes using oaswrap/spec.

Features

  • ⚡ Seamless Integration — Works with your existing Gin routes and handlers
  • 📝 Automatic Documentation — Generate OpenAPI specs from route definitions and struct tags
  • 🎯 Type Safety — Full Go type safety for OpenAPI configuration
  • 🔧 Built-in UI — Swagger UI served automatically at /docs
  • 📄 YAML Export — OpenAPI spec available at /docs/openapi.yaml
  • 🚀 Zero Overhead — Minimal performance impact on your API

Installation

go get github.com/oaswrap/spec/adapters/ginopenapi

Quick Start

package main

import (
	"log"

	"github.com/gin-gonic/gin"
	"github.com/oaswrap/spec/adapters/ginopenapi"
	"github.com/oaswrap/spec/option"
)

func main() {
	e := gin.Default()

	// Create a new OpenAPI router
	r := ginopenapi.NewRouter(e,
		option.WithTitle("My API"),
		option.WithVersion("1.0.0"),
	)
	// Add routes
	v1 := r.Group("/api/v1")

	v1.POST("/login", LoginHandler).With(
		option.Summary("User login"),
		option.Request(new(LoginRequest)),
		option.Response(200, new(LoginResponse)),
	)

	v1.GET("/users/{id}", GetUserHandler).With(
		option.Summary("Get user by ID"),
		option.Request(new(GetUserRequest)),
		option.Response(200, new(User)),
	)

	// Generate OpenAPI spec
	if err := r.WriteSchemaTo("openapi.yaml"); err != nil {
		log.Fatal(err)
	}

	log.Printf("🚀 OpenAPI docs available at: %s", "http://localhost:3000/docs")

	if err := e.Run(":3000"); err != nil {
		log.Fatal(err)
	}
}

type LoginRequest struct {
	Username string `json:"username" required:"true"`
	Password string `json:"password" required:"true"`
}

type LoginResponse struct {
	Token string `json:"token"`
}

type GetUserRequest struct {
	ID string `path:"id" required:"true"`
}

type User struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

func LoginHandler(c *gin.Context) {
	var req LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(400, map[string]string{"error": "Invalid request"})
		return
	}
	// Simulate login logic
	c.JSON(200, LoginResponse{Token: "example-token"})
}

func GetUserHandler(c *gin.Context) {
	var req GetUserRequest
	if err := c.ShouldBindUri(&req); err != nil {
		c.JSON(400, map[string]string{"error": "Invalid request"})
		return
	}
	// Simulate fetching user by ID
	user := User{ID: req.ID, Name: "John Doe"}
	c.JSON(200, user)
}

Documentation Features

Built-in Endpoints

When you create a ginopenapi router, the following endpoints are automatically available:

  • /docs — Interactive Swagger UI documentation
  • /docs/openapi.yaml — Raw OpenAPI specification in YAML format

If you want to disable the built-in UI, you can do so by passing option.WithDisableDocs() when creating the router:

r := ginopenapi.NewRouter(c,
	option.WithTitle("My API"),
	option.WithVersion("1.0.0"),
	option.WithDisableDocs(),
)
Rich Schema Documentation

Use struct tags to generate detailed OpenAPI schemas:

type CreateProductRequest struct {
	Name        string   `json:"name" required:"true" minLength:"1" maxLength:"100"`
	Description string   `json:"description" maxLength:"500"`
	Price       float64  `json:"price" required:"true" minimum:"0" maximum:"999999.99"`
	Category    string   `json:"category" required:"true" enum:"electronics,books,clothing"`
	Tags        []string `json:"tags" maxItems:"10"`
	InStock     bool     `json:"in_stock" default:"true"`
}

For more struct tag options, see the swaggest/openapi-go.

Examples

Check out complete examples in the main repository:

Best Practices

  1. Organize with Tags — Group related operations using option.Tags()
  2. Document Everything — Use option.Summary() and option.Description() for all routes
  3. Define Error Responses — Include common error responses (400, 401, 404, 500)
  4. Use Validation Tags — Leverage struct tags for request validation documentation
  5. Security First — Define and apply appropriate security schemes
  6. Version Your API — Use route groups for API versioning (/api/v1, /api/v2)

API Reference

Contributing

We welcome contributions! Please open issues and PRs at the main oaswrap/spec repository.

License

MIT License — Created with ❤️ by Ahmad Faiz.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Generator

type Generator interface {
	Router

	// Validate checks if the OpenAPI specification is valid.
	Validate() error

	// GenerateSchema generates the OpenAPI schema.
	// Defaults to YAML. Pass "json" to generate JSON.
	GenerateSchema(format ...string) ([]byte, error)

	// MarshalYAML marshals the OpenAPI schema to YAML.
	MarshalYAML() ([]byte, error)

	// MarshalJSON marshals the OpenAPI schema to JSON.
	MarshalJSON() ([]byte, error)

	// WriteSchemaTo writes the schema to the given file.
	// The format is inferred from the file extension.
	WriteSchemaTo(filepath string) error
}

Generator defines an Gin-compatible OpenAPI generator.

It combines routing and OpenAPI schema generation.

func NewGenerator

func NewGenerator(ginRouter gin.IRouter, opts ...option.OpenAPIOption) Generator

NewGenerator returns a new OpenAPI generator for Gin.

It sets up the OpenAPI configuration and prepares the routes for serving docs.

func NewRouter

func NewRouter(ginRouter gin.IRouter, opts ...option.OpenAPIOption) Generator

NewRouter returns a new Gin router with OpenAPI support.

It configures the OpenAPI generator and attaches the routes for serving docs.

type Route

type Route interface {
	// With applies OpenAPI operation options to this route.
	With(opts ...option.OperationOption) Route
}

Route represents a single Echo route with OpenAPI metadata.

type Router

type Router interface {
	// Handle registers a new route with the given method, path, and handler.
	Handle(method string, path string, handlers ...gin.HandlerFunc) Route

	// GET registers a new GET route.
	GET(path string, handlers ...gin.HandlerFunc) Route

	// POST registers a new POST route.
	POST(path string, handlers ...gin.HandlerFunc) Route

	// DELETE registers a new DELETE route.
	DELETE(path string, handlers ...gin.HandlerFunc) Route

	// PATCH registers a new PATCH route.
	PATCH(path string, handlers ...gin.HandlerFunc) Route

	// PUT registers a new PUT route.
	PUT(path string, handlers ...gin.HandlerFunc) Route

	// OPTIONS registers a new OPTIONS route.
	OPTIONS(path string, handlers ...gin.HandlerFunc) Route

	// HEAD registers a new HEAD route.
	HEAD(path string, handlers ...gin.HandlerFunc) Route

	// Group creates a new sub-group with the given prefix and middleware.
	Group(prefix string, handlers ...gin.HandlerFunc) Router

	// Use adds global middleware.
	Use(middlewares ...gin.HandlerFunc) Router

	// StaticFile serves a single static file.
	StaticFile(path string, filepath string) Router

	// StaticFileFS serves a static file from the given filesystem.
	StaticFileFS(path string, filepath string, fs http.FileSystem) Router

	// Static serves static files from a directory under the given prefix.
	Static(path string, root string) Router

	// StaticFS serves static files from the given filesystem.
	StaticFS(path string, fs http.FileSystem) Router

	// With applies OpenAPI group options to this router.
	With(opts ...option.GroupOption) Router
}

Router defines an OpenAPI-aware Gin router.

It wraps Gin routes and supports OpenAPI metadata.

Directories

Path Synopsis
examples
basic command
internal

Jump to

Keyboard shortcuts

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