chiopenapi

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2025 License: MIT Imports: 8 Imported by: 0

README

chiopenapi

Go Reference

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

Why chiopenapi?

  • ⚡ Seamless Integration — Works with your existing Chi 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
  • 🚀 Zero Overhead — Minimal performance impact on your API

Installation

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

Quick Start

package main

import (
	"encoding/json"
	"log"
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/oaswrap/spec/adapters/chiopenapi"
	"github.com/oaswrap/spec/option"
)

func main() {
	c := chi.NewRouter()
	// Create a new OpenAPI router
	r := chiopenapi.NewRouter(c,
		option.WithTitle("My API"),
		option.WithVersion("1.0.0"),
	)
	// Add routes
	r.Route("/api/v1", func(r chiopenapi.Router) {
		r.Post("/login", LoginHandler).With(
			option.Summary("User login"),
			option.Request(new(LoginRequest)),
			option.Response(200, new(LoginResponse)),
		)

		r.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")

	// Start the server
	if err := http.ListenAndServe(":3000", c); 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(w http.ResponseWriter, r *http.Request) {
	var req LoginRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "Invalid request", http.StatusBadRequest)
		return
	}
	// Simulate login logic
	_ = json.NewEncoder(w).Encode(LoginResponse{Token: "example-token"})
}

func GetUserHandler(w http.ResponseWriter, r *http.Request) {
	var req GetUserRequest
	id := chi.URLParam(r, "id")
	if id == "" {
		http.Error(w, "User ID is required", http.StatusBadRequest)
		return
	}
	req.ID = id
	// Simulate fetching user by ID
	user := User{ID: req.ID, Name: "John Doe"}
	_ = json.NewEncoder(w).Encode(user)
}

Advanced Features

Route Groups with Common Settings
// Apply settings to all routes in a group
adminAPI := api.Group("/admin").With(
    option.GroupTags("Administration"),
    option.GroupSecurity("bearerAuth"),
)

adminAPI.GET("/users", getUsersHandler).With(
    option.Summary("List all users"),
    option.Response(200, new([]User)),
)

Configuration Options

For all available configuration options, see the main oaswrap/spec documentation.

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 schema is valid.
	Validate() error

	// GenerateSchema generates the OpenAPI schema in the specified formats.
	// Supported formats include "yaml", "json", etc.
	// If no formats are specified, it defaults to "yaml".
	GenerateSchema(formats ...string) ([]byte, error)

	// MarshalYAML generates the OpenAPI schema in YAML format.
	MarshalYAML() ([]byte, error)

	// MarshalJSON generates the OpenAPI schema in JSON format.
	MarshalJSON() ([]byte, error)

	// WriteSchemaTo writes the OpenAPI schema to a file in the specified format.
	WriteSchemaTo(filename string) error
}

Generator is an interface that defines methods for generating OpenAPI schemas

func NewGenerator

func NewGenerator(r chi.Router, opts ...option.OpenAPIOption) Generator

NewGenerator creates a new OpenAPI generator with the specified Chi router and options.

It initializes the OpenAPI configuration and sets up the necessary handlers for OpenAPI documentation.

func NewRouter

func NewRouter(r chi.Router, opts ...option.OpenAPIOption) Generator

NewRouter creates a new OpenAPI router with the specified Chi router and options.

It initializes the OpenAPI generator and sets up the necessary handlers for OpenAPI documentation.

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 {
	// Use applies middleware to the router.
	Use(middlewares ...func(http.Handler) http.Handler)

	// With applies middleware to the router and returns a new Router instance.
	With(middlewares ...func(http.Handler) http.Handler) Router

	// Group creates a new sub-router with the specified options.
	Group(fn func(r Router), opts ...option.GroupOption) Router

	// Route creates a new sub-router for the specified pattern.
	Route(pattern string, fn func(r Router), opts ...option.GroupOption) Router

	// Mount mounts a sub-router at the specified pattern.
	Mount(pattern string, h http.Handler)

	// Handle registers a handler for the specified pattern.
	Handle(pattern string, h http.Handler)
	HandleFunc(pattern string, h http.HandlerFunc)

	// Method registers a handler for the specified HTTP method and pattern.
	Method(method, pattern string, h http.Handler) Route
	MethodFunc(method, pattern string, h http.HandlerFunc) Route

	// HTTP methods
	Connect(pattern string, h http.HandlerFunc) Route
	Delete(pattern string, h http.HandlerFunc) Route
	Get(pattern string, h http.HandlerFunc) Route
	Head(pattern string, h http.HandlerFunc) Route
	Options(pattern string, h http.HandlerFunc) Route
	Patch(pattern string, h http.HandlerFunc) Route
	Post(pattern string, h http.HandlerFunc) Route
	Put(pattern string, h http.HandlerFunc) Route
	Trace(pattern string, h http.HandlerFunc) Route

	// NotFound sets the handler for 404 Not Found responses.
	NotFound(h http.HandlerFunc)
	// MethodNotAllowed sets the handler for 405 Method Not Allowed responses.
	MethodNotAllowed(h http.HandlerFunc)

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

Router is an interface that defines methods for handling HTTP routes with OpenAPI support.

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