fiberopenapi

package module
v0.2.1 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

fiberopenapi

Go Reference

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

Why fiberopenapi?

  • ⚡ Seamless Integration — Works with your existing Fiber 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/fiberopenapi

Quick Start

package main

import (
	"log"

	"github.com/gofiber/fiber/v2"
	"github.com/oaswrap/spec/adapters/fiberopenapi"
	"github.com/oaswrap/spec/option"
)

func main() {
	app := fiber.New()

	// Create a new OpenAPI router
	r := fiberopenapi.NewRouter(app,
		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.Println("✅ OpenAPI spec generated at openapi.yaml")
}

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 *fiber.Ctx) error {
	var req LoginRequest
	if err := c.BodyParser(&req); err != nil {
		return c.Status(400).JSON(map[string]string{"error": "Invalid request"})
	}
	// Simulate login logic
	return c.Status(200).JSON(LoginResponse{Token: "example-token"})
}

func GetUserHandler(c *fiber.Ctx) error {
	var req GetUserRequest
	if err := c.ParamsParser(&req); err != nil {
		return c.Status(400).JSON(map[string]string{"error": "Invalid request"})
	}
	// Simulate fetching user by ID
	user := User{ID: req.ID, Name: "John Doe"}
	return c.Status(200).JSON(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 for errors at OpenAPI router initialization.
	Validate() error

	// GenerateOpenAPISchema generates the OpenAPI schema in the specified format.
	GenerateOpenAPISchema(format ...string) ([]byte, error)
	// MarshalYAML marshals the OpenAPI schema to YAML format.
	MarshalYAML() ([]byte, error)
	// MarshalJSON marshals the OpenAPI schema to JSON format.
	MarshalJSON() ([]byte, error)

	// WriteSchemaTo writes the OpenAPI schema to a file.
	WriteSchemaTo(filePath string) error
}

Generator defines the interface for generating OpenAPI schemas.

func NewGenerator

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

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

It initializes the OpenAPI router and sets up the necessary routes for OpenAPI documentation.

func NewRouter

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

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

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

type Route

type Route interface {
	// Name sets the name for the route.
	Name(name string) Route
	// With applies the given options to the route.
	With(opts ...option.OperationOption) Route
}

Route represents a single route in the OpenAPI specification.

type Router

type Router interface {
	// Use applies middleware to the router.
	Use(args ...any) Router

	// Get registers a GET route.
	Get(path string, handler ...fiber.Handler) Route
	// Head registers a HEAD route.
	Head(path string, handler ...fiber.Handler) Route
	// Post registers a POST route.
	Post(path string, handler ...fiber.Handler) Route
	// Put registers a PUT route.
	Put(path string, handler ...fiber.Handler) Route
	// Patch registers a PATCH route.
	Patch(path string, handler ...fiber.Handler) Route
	// Delete registers a DELETE route.
	Delete(path string, handler ...fiber.Handler) Route
	// Connect registers a CONNECT route.
	Connect(path string, handler ...fiber.Handler) Route
	// Options registers an OPTIONS route.
	Options(path string, handler ...fiber.Handler) Route
	// Trace registers a TRACE route.
	Trace(path string, handler ...fiber.Handler) Route

	// Add registers a route with the specified method and path.
	Add(method, path string, handler ...fiber.Handler) Route
	// Static serves static files from the specified root directory.
	Static(prefix, root string, config ...fiber.Static) Router

	// Group creates a new sub-router with the specified prefix and handlers.
	// The prefix is prepended to all routes in the sub-router.
	Group(prefix string, handlers ...fiber.Handler) Router

	// Route creates a new sub-router with the specified prefix and applies options.
	Route(prefix string, fn func(router Router)) Router

	// With applies options to the router.
	// This allows you to configure tags, security, and visibility for the routes.
	With(opts ...option.GroupOption) Router
}

Router defines the interface for an OpenAPI router.

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