ginopenapi

package module
v0.1.0 Latest Latest
Warning

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

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

README

ginopenapi

CI codecov Go Reference Go Report Card License

ginopenapi is a minimal adapter for the Gin web framework that connects your routes to an OpenAPI 3.x specification using oaswrap/spec.

This package lets you define your Gin routes and generate OpenAPI docs automatically — with simple, chainable options.

The underlying spec builder uses swaggest/openapi-go — a robust OpenAPI 3.0/3.1 generator for Go with support for struct tags.

✨ Features

  • ✅ Integrates Gin routes with an OpenAPI spec.
  • ✅ Uses oaswrap/spec powered by swaggest/openapi-go.
  • ✅ Supports struct tags for request/response models — automatically maps field properties, examples, and validation.
  • ✅ Define common route metadata: summary, description, tags, security, request/response models.
  • ✅ Built-in validation and schema generation helpers.

📦 Installation

go get github.com/oaswrap/ginopenapi

⚡️ Quick Start

package main

import (
	"log"

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

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

	// Optional: Add CORS middleware
	r.Use(cors.New(cors.Config{
		AllowOrigins: []string{"*"},
	}))

	// Setup OpenAPI router
	api := ginopenapi.NewRouter(r,
		option.WithTitle("Example API"),
		option.WithVersion("1.0.0"),
		option.WithDescription("Sample Gin + OpenAPI"),
		option.WithOpenAPIVersion("3.0.3"),
		option.WithServer("http://localhost:8080"),
	)

	// Define a simple group and route
	v1 := api.Group("/api/v1")
	v1.POST("/hello", helloHandler).With(
		option.Summary("Say Hello"),
		option.Request(new(HelloRequest)),
		option.Response(200, new(HelloResponse)),
	)

	// Write spec file (optional)
	if err := api.WriteSchemaTo("openapi.yaml"); err != nil {
		log.Fatal(err)
	}
	log.Println("✅ OpenAPI schema written to: openapi.yaml")

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

	r.Run(":8080")
}

// helloHandler handles the /api/v1/hello route
func helloHandler(c *gin.Context) {
	var req HelloRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(400, gin.H{"error": "Invalid request body"})
		return
	}
	c.JSON(200, HelloResponse{
		Message: "Hello, " + req.Name,
	})
}

// Request and response types
type HelloRequest struct {
	Name string `json:"name" example:"World" binding:"required"`
}

type HelloResponse struct {
	Message string `json:"message" example:"Hello, World"`
}

For a full working version, see the examples directory.

This example demonstrates:

  • Nested groups (/pets)
  • Multiple HTTP methods (GET, POST, PUT, DELETE)
  • With options for detailed spec generation
  • Use of struct tags to enrich models automatically.

📚 Documentation

🤝 Contributing

PRs and issues welcome!
If you find bugs or want to improve adapters or helpers, please open an issue.

📄 License

MIT

Made with ❤️ by oaswrap

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewGenerator

func NewGenerator(opts ...option.OpenAPIOption) spec.Generator

NewGenerator creates a new OpenAPI generator with the specified options.

It initializes the OpenAPI handler and sets up the necessary routes.

The generator can be used to define API endpoints and generate OpenAPI documentation.

Types

type Generator

type Generator interface {
	Router

	// Validate checks if the OpenAPI spec is valid.
	Validate() error
	// GenerateOpenAPISchema generates the OpenAPI schema in the specified format(s).
	GenerateOpenAPISchema(format ...string) ([]byte, error)
	// MarshalYAML marshals the OpenAPI specification to YAML format.
	MarshalYAML() ([]byte, error)
	// MarshalJSON marshals the OpenAPI specification to JSON format.
	MarshalJSON() ([]byte, error)
	// WriteSchemaTo writes the OpenAPI schema to the specified file path.
	WriteSchemaTo(filepath string) error
}

Generator embeds Router and adds OpenAPI-specific methods.

func NewRouter

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

NewRouter creates a new Gin router with OpenAPI support.

It initializes the OpenAPI handler and sets up the necessary routes.

The router can be used to define API endpoints and generate OpenAPI documentation.

type Route

type Route interface {
	// With applies the specified options to the route.
	With(opts ...option.OperationOption) Route
}

Route defines the interface for a single route.

type Router

type Router interface {
	// Handle registers a new route with the specified method and path, and returns a Route object.
	Handle(method string, path string, handlers ...gin.HandlerFunc) Route
	// GET registers a new GET route with the specified path and handlers.
	GET(path string, handlers ...gin.HandlerFunc) Route
	// POST registers a new POST route with the specified path and handlers.
	POST(path string, handlers ...gin.HandlerFunc) Route
	// DELETE registers a new DELETE route with the specified path and handlers.
	DELETE(path string, handlers ...gin.HandlerFunc) Route
	// PATCH registers a new PATCH route with the specified path and handlers.
	PATCH(path string, handlers ...gin.HandlerFunc) Route
	// PUT registers a new PUT route with the specified path and handlers.
	PUT(path string, handlers ...gin.HandlerFunc) Route
	// OPTIONS registers a new OPTIONS route with the specified path and handlers.
	OPTIONS(path string, handlers ...gin.HandlerFunc) Route
	// HEAD registers a new HEAD route with the specified path and handlers.
	HEAD(path string, handlers ...gin.HandlerFunc) Route

	// Group creates a new route group with the specified prefix and handlers.
	Group(prefix string, handlers ...gin.HandlerFunc) Router
	// Use adds middleware to the router.
	Use(middlewares ...gin.HandlerFunc) Router

	// StaticFile serves a single file at the specified path.
	StaticFile(path string, filepath string) Router
	// StaticFileFS serves a single file at the specified path using the provided file system.
	StaticFileFS(path string, filepath string, fs http.FileSystem) Router
	// Static serves static files from the specified root directory.
	Static(path string, root string) Router
	// StaticFS serves static files from the specified file system at the given path.
	StaticFS(path string, fs http.FileSystem) Router

	// With applies OpenAPI group-level options.
	With(opts ...option.GroupOption) Router
}

Router defines the interface for a Gin router with OpenAPI support.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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