autofiber

package module
v0.5.6 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2026 License: MIT Imports: 10 Imported by: 0

README

AutoFiber

CI codecov Go Report Card Go Version License

A FastAPI-like wrapper for Fiber that adds automatic request parsing, validation, and OpenAPI/Swagger documentation — from struct tags alone.

Features

  • Multi-source parsing — body, query, path, header, cookie, form via a single parse tag
  • Automatic validationgo-playground/validator/v10 applied on every request
  • OpenAPI 3.0 docs — generated from struct tags; served as Swagger UI
  • JWT auth — declare once per route or group; runtime 401 on missing header
  • Group middleware — attach middleware or JWT auth to an entire route group
  • Custom error handler — control how validation errors are formatted
  • Custom validators — register per-instance validation tags
  • File downloads — return CSV/PDF responses, bypassing JSON serialization
  • Response validation — validate outgoing data against a schema before sending

Installation

go get github.com/vuongtlt13/auto-fiber

Quick Start

package main

import (
    "github.com/gofiber/fiber/v2"
    autofiber "github.com/vuongtlt13/auto-fiber"
)

type CreateUserRequest struct {
    OrgID int    `parse:"path:org_id"  validate:"required"`
    Role  string `parse:"query:role"   validate:"required,oneof=admin user"`
    Email string `json:"email"         validate:"required,email"`
    Name  string `json:"name"          validate:"required"`
}

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

func createUser(c *fiber.Ctx, req *CreateUserRequest) (interface{}, error) {
    return UserResponse{ID: 1, Email: req.Email, Name: req.Name, Role: req.Role}, nil
}

func main() {
    app := autofiber.New(fiber.Config{},
        autofiber.WithOpenAPI(autofiber.OpenAPIInfo{
            Title:   "My API",
            Version: "1.0.0",
        }),
    )

    app.Post("/orgs/:org_id/users", createUser,
        autofiber.WithRequestSchema(CreateUserRequest{}),
        autofiber.WithResponseSchema(UserResponse{}),
        autofiber.WithTags("users"),
    )

    app.ServeDocs("/docs")
    app.ServeSwaggerUI("/swagger", "/docs")
    app.Listen(":3000")
}

What You Get

Successful request
POST /orgs/42/users?role=admin
Content-Type: application/json

{"email": "jane@example.com", "name": "Jane Doe"}
{
  "id": 1,
  "email": "jane@example.com",
  "name": "Jane Doe",
  "role": "admin"
}
Automatic validation error

Send an invalid request — missing name, invalid email, unknown role:

POST /orgs/42/users?role=superadmin
Content-Type: application/json

{"email": "not-an-email"}
HTTP 422 Unprocessable Entity
{
  "message": "Validation failed",
  "details": [
    {
      "field": "CreateUserRequest.Role",
      "message": "Key: 'CreateUserRequest.Role' Error:Field validation for 'Role' failed on the 'oneof' tag",
      "tag": "oneof"
    },
    {
      "field": "CreateUserRequest.Email",
      "message": "Key: 'CreateUserRequest.Email' Error:Field validation for 'Email' failed on the 'email' tag",
      "tag": "email"
    },
    {
      "field": "CreateUserRequest.Name",
      "message": "Key: 'CreateUserRequest.Name' Error:Field validation for 'Name' failed on the 'required' tag",
      "tag": "required"
    }
  ]
}

No error-handling code needed in your handler — AutoFiber generates this from the validate tags.

Auto-generated OpenAPI spec

GET /docs returns a complete OpenAPI 3.0 document. The POST /orgs/{org_id}/users operation looks like:

{
  "paths": {
    "/orgs/{org_id}/users": {
      "post": {
        "tags": ["users"],
        "parameters": [
          { "name": "org_id", "in": "path",  "required": true, "schema": { "type": "integer" } },
          { "name": "role",   "in": "query", "required": true, "schema": { "type": "string", "enum": ["admin", "user"] } }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/CreateUserRequest" }
            }
          }
        },
        "responses": {
          "200": {
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/UserResponse" }
              }
            }
          }
        }
      }
    }
  }
}

Visit /swagger for the interactive Swagger UI where you can try every endpoint directly in the browser.

How It Works

Every request passes through a fixed pipeline built once at registration time — nothing is computed per-request beyond reading the actual values.

Incoming HTTP request
        │
        ▼
┌───────────────────┐
│   Middleware      │  group middleware → route middleware
└────────┬──────────┘
         │
         ▼
┌───────────────────┐
│  Parse Request    │  body (JSON/form) · path · query · header · cookie
│                   │  driven by `parse` struct tags, cached at startup
└────────┬──────────┘
         │  ParseError → 400
         ▼
┌───────────────────┐
│ Validate Request  │  go-playground/validator · `validate` struct tags
└────────┬──────────┘
         │  ValidationError → 422
         ▼
┌───────────────────┐
│  Your Handler     │  func(c *fiber.Ctx, req *T) (interface{}, error)
└────────┬──────────┘
         │  error → Fiber error handler
         ▼
┌───────────────────┐
│ Validate Response │  optional · `validate` tags on response struct
└────────┬──────────┘
         │
         ▼
     JSON / File

At startup, AutoFiber also walks all registered route schemas to emit a fully-typed OpenAPI 3.0 spec — no runtime reflection during requests.

Documentation

Topic Description
Routing Route registration, groups, group middleware
Request Parsing parse tags, sources, embedded structs, defaults
Validation Built-in rules, patterns
Custom Validators Per-instance custom validation tags
Authentication JWT auth, WithJwtAuth, schema-inferred auth
Error Handling Custom error format, error types
Complete Flow End-to-end request/response lifecycle
Migration Guide Migrate from older handler signatures

License

MIT

Documentation

Overview

Package autofiber provides a FastAPI-like wrapper for the Fiber web framework. It enables automatic request parsing, validation, and OpenAPI/Swagger documentation generation.

Package autofiber provides OpenAPI 3.0 specification generation for automatic API documentation.

Package autofiber provides OpenAPI/Swagger documentation configuration and serving utilities.

Package autofiber provides route group functionality with automatic request parsing, validation, and documentation generation.

Package autofiber provides handler creation utilities for automatic request parsing, validation, and response handling.

Package autofiber provides map and interface parsing utilities for converting data structures to Go structs.

Package autofiber provides middleware functions for automatic request parsing, validation, and response handling.

Package autofiber provides route configuration options for building APIs with automatic parsing, validation, and documentation.

Package autofiber provides request parsing utilities for extracting and validating data from multiple sources.

Package autofiber provides HTTP route registration methods with automatic request parsing, validation, and documentation generation.

Package autofiber provides core types and configuration for the AutoFiber web framework.

Package autofiber provides response validation utilities for ensuring API responses match expected schemas.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AutoParseRequest

func AutoParseRequest(schema interface{}, customValidator *validator.Validate) fiber.Handler

AutoParseRequest returns middleware for automatic request parsing and validation. The middleware parses request data from multiple sources (body, query, path, headers, cookies, form) based on struct tags and validates the parsed data using the provided schema. If customValidator is nil, it uses the global validator instance.

Schema metadata (field info, parse tags) is pre-computed here at registration time, not on every request.

func GenerateOperationID added in v0.3.4

func GenerateOperationID(method, path string, handler interface{}) string

GenerateOperationID generates a unique operation ID for the OpenAPI specification. It combines the HTTP method and path to create a unique identifier (no handler signature).

func GetParsedRequest

func GetParsedRequest[T any](c *fiber.Ctx) *T

GetParsedRequest retrieves the parsed request from context. This function extracts the parsed request data that was stored by AutoParseRequest middleware. It returns nil if no parsed request is found or if the type assertion fails.

func GetSchemaName added in v0.3.4

func GetSchemaName(schema interface{}) string

GetSchemaName gets the name of a schema from its Go type. It handles pointer types and returns the underlying type name. For generic structs, it generates a unique name including type parameters (e.g., APIResponse_User).

func GetSchemaNameFromRef added in v0.4.1

func GetSchemaNameFromRef(ref string) string

GetSchemaNameFromRef extracts the schema name from an OpenAPI reference string. It handles references in the format "#/components/schemas/SchemaName".

func GetValidator

func GetValidator() *validator.Validate

GetValidator returns the global validator instance for validation.

func ParseFromInterface

func ParseFromInterface(data interface{}, schema interface{}) error

ParseFromInterface parses a struct from any interface{} (map, struct, etc.). It supports map[string]interface{}, map[string]string, and struct types. The schema parameter must be a pointer to the target struct.

func ParseFromMap

func ParseFromMap(data map[string]interface{}, schema interface{}) error

ParseFromMap parses a struct from a map[string]interface{}. It uses JSON tags to map keys to struct fields and sets the values accordingly. The schema parameter must be a pointer to the target struct.

func ValidateAndJSON

func ValidateAndJSON(c *fiber.Ctx, data interface{}) error

ValidateAndJSON validates response data and returns JSON. If response validation is configured, it validates the data against the response schema before returning the JSON response. If validation fails, it returns an error response. If no validation is configured, it simply returns the JSON response.

func ValidateStruct added in v0.4.8

func ValidateStruct[T any](m *T) error

ValidateStruct is a helper that validates any struct using the global validator. It is especially convenient to use from your domain models or services:

type User struct {
    Email string `json:"email" validate:"required,email"`
    Age   int    `json:"age" validate:"gte=18"`
}

u := &User{Email: "test@example.com", Age: 20}
if err := autofiber.ValidateStruct(u); err != nil {
    // handle validation error
}

Types

type AutoFiber

type AutoFiber struct {
	App *fiber.App
	// contains filtered or unexported fields
}

AutoFiber is the main application struct for building APIs with automatic parsing, validation, and documentation.

func New

func New(config fiber.Config, options ...AutoFiberOption) *AutoFiber

New creates a new AutoFiber application instance with custom options.

func (*AutoFiber) All

func (af *AutoFiber) All(path string, handler interface{}, options ...RouteOption) fiber.Router

All registers a route for all HTTP methods with automatic request parsing, validation, and documentation generation. The handler can be a simple function or a function that accepts a parsed request struct. Options can be provided to configure request/response schemas, middleware, and documentation.

func (*AutoFiber) Delete

func (af *AutoFiber) Delete(path string, handler interface{}, options ...RouteOption) fiber.Router

Delete registers a DELETE route with automatic request parsing, validation, and documentation generation. The handler can be a simple function or a function that accepts a parsed request struct. Options can be provided to configure request/response schemas, middleware, and documentation.

func (*AutoFiber) Get

func (af *AutoFiber) Get(path string, handler interface{}, options ...RouteOption) fiber.Router

Get registers a GET route with automatic request parsing, validation, and documentation generation. The handler can be a simple function or a function that accepts a parsed request struct. Options can be provided to configure request/response schemas, middleware, and documentation.

func (*AutoFiber) GetOpenAPIJSON

func (af *AutoFiber) GetOpenAPIJSON() ([]byte, error)

GetOpenAPIJSON returns the OpenAPI specification as JSON bytes. This is useful for serving the specification via HTTP or saving to a file.

func (*AutoFiber) GetOpenAPISpec

func (af *AutoFiber) GetOpenAPISpec() *OpenAPISpec

GetOpenAPISpec returns the complete OpenAPI specification as a struct. If no documentation info is set, it uses default values.

func (*AutoFiber) Group

func (af *AutoFiber) Group(prefix string, handlers ...fiber.Handler) *AutoFiberGroup

Group creates a new route group with the given prefix.

func (*AutoFiber) Head

func (af *AutoFiber) Head(path string, handler interface{}, options ...RouteOption) fiber.Router

Head registers a HEAD route with automatic request parsing, validation, and documentation generation. The handler can be a simple function or a function that accepts a parsed request struct. Options can be provided to configure request/response schemas, middleware, and documentation.

func (*AutoFiber) Listen

func (af *AutoFiber) Listen(addr string) error

Listen starts the Fiber application on the specified address.

func (*AutoFiber) Options

func (af *AutoFiber) Options(path string, handler interface{}, options ...RouteOption) fiber.Router

Options registers an OPTIONS route with automatic request parsing, validation, and documentation generation. The handler can be a simple function or a function that accepts a parsed request struct. Options can be provided to configure request/response schemas, middleware, and documentation.

func (*AutoFiber) Patch

func (af *AutoFiber) Patch(path string, handler interface{}, options ...RouteOption) fiber.Router

Patch registers a PATCH route with automatic request parsing, validation, and documentation generation. The handler can be a simple function or a function that accepts a parsed request struct. Options can be provided to configure request/response schemas, middleware, and documentation.

func (*AutoFiber) Post

func (af *AutoFiber) Post(path string, handler interface{}, options ...RouteOption) fiber.Router

Post registers a POST route with automatic request parsing, validation, and documentation generation. The handler can be a simple function or a function that accepts a parsed request struct. Options can be provided to configure request/response schemas, middleware, and documentation.

func (*AutoFiber) Put

func (af *AutoFiber) Put(path string, handler interface{}, options ...RouteOption) fiber.Router

Put registers a PUT route with automatic request parsing, validation, and documentation generation. The handler can be a simple function or a function that accepts a parsed request struct. Options can be provided to configure request/response schemas, middleware, and documentation.

func (*AutoFiber) RegisterValidator added in v0.5.2

func (af *AutoFiber) RegisterValidator(tag string, fn validator.Func) error

RegisterValidator registers a custom validation function on the instance's validator. Use this after New() to add validations that should apply to all routes on this instance.

func (*AutoFiber) ServeDocs

func (af *AutoFiber) ServeDocs(path string)

ServeDocs serves the OpenAPI specification as JSON at the specified path. This creates a GET route that returns the OpenAPI specification.

func (*AutoFiber) ServeSwaggerUI

func (af *AutoFiber) ServeSwaggerUI(swaggerPath, docsPath string)

ServeSwaggerUI serves Swagger UI for the OpenAPI documentation. This creates a GET route that serves an HTML page with Swagger UI interface. swaggerPath is the URL path where Swagger UI will be served. docsPath is the URL path where the OpenAPI JSON specification is served.

func (*AutoFiber) Test

func (af *AutoFiber) Test(req *http.Request, msTimeout ...int) (*http.Response, error)

Test creates a test request for the Fiber application.

func (*AutoFiber) Use

func (af *AutoFiber) Use(args ...interface{}) fiber.Router

Use adds middleware to the app.

type AutoFiberGroup

type AutoFiberGroup struct {
	Group *fiber.Group // Underlying Fiber group

	Prefix string // Prefix of the group
	// contains filtered or unexported fields
}

AutoFiberGroup represents a group of routes with a common prefix and shared middleware.

func (*AutoFiberGroup) All

func (ag *AutoFiberGroup) All(path string, handler interface{}, options ...RouteOption) fiber.Router

All registers a route for all HTTP methods in the group.

func (*AutoFiberGroup) Delete

func (ag *AutoFiberGroup) Delete(path string, handler interface{}, options ...RouteOption) fiber.Router

Delete registers a DELETE route in the group.

func (*AutoFiberGroup) Get

func (ag *AutoFiberGroup) Get(path string, handler interface{}, options ...RouteOption) fiber.Router

Get registers a GET route in the group.

func (*AutoFiberGroup) Head

func (ag *AutoFiberGroup) Head(path string, handler interface{}, options ...RouteOption) fiber.Router

Head registers a HEAD route in the group.

func (*AutoFiberGroup) Options

func (ag *AutoFiberGroup) Options(path string, handler interface{}, options ...RouteOption) fiber.Router

Options registers an OPTIONS route in the group.

func (*AutoFiberGroup) Patch

func (ag *AutoFiberGroup) Patch(path string, handler interface{}, options ...RouteOption) fiber.Router

Patch registers a PATCH route in the group.

func (*AutoFiberGroup) Post

func (ag *AutoFiberGroup) Post(path string, handler interface{}, options ...RouteOption) fiber.Router

Post registers a POST route in the group.

func (*AutoFiberGroup) Put

func (ag *AutoFiberGroup) Put(path string, handler interface{}, options ...RouteOption) fiber.Router

Put registers a PUT route in the group.

func (*AutoFiberGroup) Use

func (ag *AutoFiberGroup) Use(args ...interface{}) fiber.Router

Use adds middleware to the underlying fiber group (applies to all sub-routes).

func (*AutoFiberGroup) WithJwtAuth added in v0.5.2

func (ag *AutoFiberGroup) WithJwtAuth() *AutoFiberGroup

WithJwtAuth marks every route registered in this group as requiring HTTP Bearer (JWT) auth. Returns the group for chaining.

Example:

protected := app.Group("/admin").WithJwtAuth()
protected.Get("/dashboard", handler)

func (*AutoFiberGroup) WithMiddleware added in v0.5.2

func (ag *AutoFiberGroup) WithMiddleware(middleware ...fiber.Handler) *AutoFiberGroup

WithMiddleware adds middleware that will be prepended to every route registered in this group. Returns the group for chaining.

Example:

api := app.Group("/api").WithMiddleware(rateLimitMiddleware, loggingMiddleware)
api.Get("/users", handler)

type AutoFiberOption added in v0.3.0

type AutoFiberOption func(*AutoFiber)

AutoFiberOption is a function type for configuring AutoFiber options.

func WithErrorHandler added in v0.5.2

func WithErrorHandler(fn func(*fiber.Ctx, error) error) AutoFiberOption

WithErrorHandler sets a custom error handler for request/response validation errors. When set, validation errors are passed through fn instead of being returned directly. This lets you control the response format for validation failures.

Example:

app := autofiber.New(fiber.Config{}, autofiber.WithErrorHandler(func(c *fiber.Ctx, err error) error {
    return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": err.Error()})
}))

func WithOpenAPI added in v0.3.0

func WithOpenAPI(info OpenAPIInfo) AutoFiberOption

WithOpenAPI sets the OpenAPI info for the documentation.

func WithValidatorSetup added in v0.5.2

func WithValidatorSetup(fn func(*validator.Validate)) AutoFiberOption

WithValidatorSetup runs fn against the instance's validator immediately after creation, allowing custom validation tags to be registered on the instance validator.

Example:

app := autofiber.New(fiber.Config{}, autofiber.WithValidatorSetup(func(v *validator.Validate) {
    v.RegisterValidation("strong_password", validateStrongPassword)
}))

type DocsGenerator

type DocsGenerator struct {
	DocsInfo *OpenAPIInfo
	// contains filtered or unexported fields
}

DocsGenerator handles API documentation generation and OpenAPI specification creation.

func NewDocsGenerator

func NewDocsGenerator() *DocsGenerator

NewDocsGenerator creates a new documentation generator with the specified base path.

func (*DocsGenerator) AddRoute

func (dg *DocsGenerator) AddRoute(path, method string, handler interface{}, options *RouteOptions)

AddRoute adds a route to the documentation generator with its metadata and options.

func (*DocsGenerator) ConvertRequestToOpenAPISchema added in v0.4.0

func (dg *DocsGenerator) ConvertRequestToOpenAPISchema(schema interface{}) OpenAPISchema

ConvertRequestToOpenAPISchema converts a Go struct to OpenAPI schema for request parsing. It prioritizes parse tags for field names, falls back to json tags, and handles validation.

func (*DocsGenerator) ConvertResponseToOpenAPISchema added in v0.4.0

func (dg *DocsGenerator) ConvertResponseToOpenAPISchema(schema interface{}) OpenAPISchema

ConvertResponseToOpenAPISchema converts a Go struct to OpenAPI schema for response serialization. It uses json tags for field names, falls back to camelCase field names, and handles validation.

func (*DocsGenerator) ConvertToOpenAPISchema added in v0.3.6

func (dg *DocsGenerator) ConvertToOpenAPISchema(schema interface{}) OpenAPISchema

ConvertToOpenAPISchema converts a Go struct to OpenAPI schema. It analyzes struct fields, their types, tags, and validation rules to create a complete schema. This is a legacy function that defaults to request conversion behavior.

func (*DocsGenerator) GenerateJSON

func (dg *DocsGenerator) GenerateJSON() ([]byte, error)

GenerateJSON generates the OpenAPI specification as JSON bytes. This is useful for serving the specification via HTTP or saving to a file.

func (*DocsGenerator) GenerateOpenAPISpec

func (dg *DocsGenerator) GenerateOpenAPISpec() *OpenAPISpec

GenerateOpenAPISpec generates the complete OpenAPI specification from collected route information.

func (*DocsGenerator) Schemas added in v0.3.6

func (dg *DocsGenerator) Schemas() map[string]OpenAPISchema

type DownloadFile added in v0.5.1

type DownloadFile struct {
	// Path is the absolute or relative path to the file on disk.
	Path string
	// FileName is an optional suggested name for the downloaded file.
	// If empty and Inline is false, Fiber will use the file name from Path.
	FileName string
	// Inline controls how the browser handles the file:
	// - true  => c.SendFile (typically displayed inline if browser supports it)
	// - false => c.Download (sent as an attachment)
	Inline bool
}

DownloadFile is a helper implementation of FileResponse that uses Fiber's Download/SendFile.

Usage in handler:

func (h *Handler) Download(c *fiber.Ctx) (interface{}, error) {
    return autofiber.DownloadFile{
        Path:     "./files/report.pdf", // required
        FileName: "report.pdf",         // optional suggested filename
        Inline:   false,                // false => attachment (Download), true => inline (SendFile)
    }, nil
}

func (DownloadFile) SendFileResponse added in v0.5.1

func (d DownloadFile) SendFileResponse(c *fiber.Ctx) error

SendFileResponse implements FileResponse using Fiber's SendFile/Download helpers.

type FieldErrorDetail added in v0.4.4

type FieldErrorDetail struct {
	Field   string `json:"field"`
	Message string `json:"message"`
	Tag     string `json:"tag,omitempty"`
}

FieldErrorDetail represents a single field validation error

type FieldInfo

type FieldInfo struct {
	Source      ParseSource // Source to parse the field from
	Key         string      // Custom key name (e.g., "user_id" for "UserId")
	Required    bool        // Whether the field is required
	Default     interface{} // Default value if not provided
	Description string      // Description for documentation
}

FieldInfo contains parsing information for a struct field.

type FileResponse added in v0.5.1

type FileResponse interface {
	// SendFileResponse is responsible for writing the file response to Fiber context.
	SendFileResponse(c *fiber.Ctx) error
}

FileResponse is a special response type that can send a file to the client instead of returning JSON. Any value that implements this interface will be detected by AutoFiber and used to send the response directly.

type HandlerFunc

type HandlerFunc func(*fiber.Ctx) error

HandlerFunc is a Fiber handler function.

type HandlerWithRequest

type HandlerWithRequest[T any] func(*fiber.Ctx, *T) (interface{}, error)

HandlerWithRequest is a generic handler function with request parsing and response. T is the type of the parsed request struct.

type OpenAPIComponents

type OpenAPIComponents struct {
	Schemas         map[string]OpenAPISchema     `json:"schemas,omitempty"`
	SecuritySchemes map[string]map[string]string `json:"securitySchemes,omitempty"`
}

OpenAPIComponents represents reusable components like schemas and security schemes.

type OpenAPIContact

type OpenAPIContact struct {
	Name  string `json:"name,omitempty"`
	URL   string `json:"url,omitempty"`
	Email string `json:"email,omitempty"`
}

OpenAPIContact represents contact information for the API.

type OpenAPIInfo

type OpenAPIInfo struct {
	Title       string          `json:"title"`
	Description string          `json:"description,omitempty"`
	Version     string          `json:"version"`
	Contact     *OpenAPIContact `json:"contact,omitempty"`
	License     *OpenAPILicense `json:"license,omitempty"`
}

OpenAPIInfo represents the API information including title, description, version, and contact details.

type OpenAPILicense

type OpenAPILicense struct {
	Name string `json:"name"`
	URL  string `json:"url,omitempty"`
}

OpenAPILicense represents license information for the API.

type OpenAPIMediaType

type OpenAPIMediaType struct {
	Schema *OpenAPISchema `json:"schema,omitempty"`
}

OpenAPIMediaType represents media type content (e.g., application/json).

type OpenAPIOperation

type OpenAPIOperation struct {
	Tags        []string                   `json:"tags,omitempty"`
	Summary     string                     `json:"summary,omitempty"`
	Description string                     `json:"description,omitempty"`
	OperationID string                     `json:"operationId,omitempty"`
	Parameters  []OpenAPIParameter         `json:"parameters,omitempty"`
	RequestBody *OpenAPIRequestBody        `json:"requestBody,omitempty"`
	Responses   map[string]OpenAPIResponse `json:"responses"`
	Security    []map[string][]string      `json:"security,omitempty"`
}

OpenAPIOperation represents an API operation with parameters, request body, and responses.

type OpenAPIParameter

type OpenAPIParameter struct {
	Name        string         `json:"name"`
	In          string         `json:"in"`
	Description string         `json:"description,omitempty"`
	Required    bool           `json:"required,omitempty"`
	Schema      *OpenAPISchema `json:"schema,omitempty"`
}

OpenAPIParameter represents a parameter (query, path, header, cookie) for an API operation.

type OpenAPIPath

type OpenAPIPath struct {
	Get     *OpenAPIOperation `json:"get,omitempty"`
	Post    *OpenAPIOperation `json:"post,omitempty"`
	Put     *OpenAPIOperation `json:"put,omitempty"`
	Delete  *OpenAPIOperation `json:"delete,omitempty"`
	Patch   *OpenAPIOperation `json:"patch,omitempty"`
	Head    *OpenAPIOperation `json:"head,omitempty"`
	Options *OpenAPIOperation `json:"options,omitempty"`
}

OpenAPIPath represents a path in the API with all supported HTTP methods.

type OpenAPIRequestBody

type OpenAPIRequestBody struct {
	Description string                      `json:"description,omitempty"`
	Required    bool                        `json:"required,omitempty"`
	Content     map[string]OpenAPIMediaType `json:"content"`
}

OpenAPIRequestBody represents a request body for an API operation.

type OpenAPIResponse

type OpenAPIResponse struct {
	Description string                      `json:"description"`
	Content     map[string]OpenAPIMediaType `json:"content,omitempty"`
}

OpenAPIResponse represents a response for an API operation.

type OpenAPISchema

type OpenAPISchema struct {
	Type        string                   `json:"type,omitempty"`
	Format      string                   `json:"format,omitempty"`
	Description string                   `json:"description,omitempty"`
	Required    []string                 `json:"required,omitempty"`
	Properties  map[string]OpenAPISchema `json:"properties,omitempty"`
	Items       *OpenAPISchema           `json:"items,omitempty"`
	Ref         string                   `json:"$ref,omitempty"`
	Example     interface{}              `json:"example,omitempty"`
}

OpenAPISchema represents a JSON schema for request/response data structures.

type OpenAPIServer

type OpenAPIServer struct {
	URL         string `json:"url"`
	Description string `json:"description,omitempty"`
}

OpenAPIServer represents server information for the API.

type OpenAPISpec

type OpenAPISpec struct {
	OpenAPI    string                 `json:"openapi"`
	Info       OpenAPIInfo            `json:"info"`
	Servers    []OpenAPIServer        `json:"servers,omitempty"`
	Paths      map[string]OpenAPIPath `json:"paths"`
	Components OpenAPIComponents      `json:"components,omitempty"`
	Tags       []OpenAPITag           `json:"tags,omitempty"`
}

OpenAPISpec represents the OpenAPI 3.0 specification structure.

type OpenAPITag

type OpenAPITag struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

OpenAPITag represents a tag for grouping API operations.

type ParseError

type ParseError struct {
	Field   string // Name of the field
	Source  string // Source of the field (e.g., body, query)
	Message string // Error message
}

ParseError represents a parsing error for a specific field and source.

func (*ParseError) Error

func (e *ParseError) Error() string

Error returns the error message for a ParseError.

type ParseSource

type ParseSource string

ParseSource defines where a field should be parsed from (e.g., body, query, path, header, etc.).

const (
	// Body indicates the field should be parsed from the request body.
	Body ParseSource = "body"
	// Query indicates the field should be parsed from the query string.
	Query ParseSource = "query"
	// Path indicates the field should be parsed from the URL path parameters.
	Path ParseSource = "path"
	// Header indicates the field should be parsed from the request headers.
	Header ParseSource = "header"
	// Cookie indicates the field should be parsed from cookies.
	Cookie ParseSource = "cookie"
	// Form indicates the field should be parsed from form data.
	Form ParseSource = "form"
	// Auto enables smart parsing based on HTTP method and struct tags.
	Auto ParseSource = "auto"
)

type RouteInfo

type RouteInfo struct {
	Path        string
	Method      string
	Handler     interface{}
	Options     *RouteOptions
	OperationID string
}

RouteInfo stores information about a route for documentation generation.

type RouteOption

type RouteOption func(*RouteOptions)

RouteOption is a function that configures route options for an endpoint.

func WithDescription

func WithDescription(description string) RouteOption

WithDescription sets the route description for API documentation. This description will appear in the generated OpenAPI/Swagger documentation.

func WithJwtAuth added in v0.4.8

func WithJwtAuth(middlewares ...fiber.Handler) RouteOption

WithJwtAuth requires HTTP Bearer (JWT) authentication for this route: it documents the route as requiring Bearer auth (OpenAPI security) and enforces that the Authorization header is present at runtime (missing header -> 401 before the handler runs).

Optionally pass one or more middleware (e.g. a middleware that parses/validates the token and loads the current user) to run them as part of the same declaration, so the route doesn't need a separate WithMiddleware(...) call to actually enforce auth:

autofiber.WithJwtAuth(myAuthMiddleware, requireUserMiddleware)

func WithMiddleware

func WithMiddleware(middleware ...fiber.Handler) RouteOption

WithMiddleware adds middleware to the route. Multiple middleware can be added and they will be executed in the order provided.

func WithOperationID added in v0.5.6

func WithOperationID(id string) RouteOption

WithOperationID sets an explicit operation ID for the route (e.g. "role.create"), used both in the generated OpenAPI spec and as a stable key for consumers that walk the spec to build their own catalogs (e.g. a permission registry keyed by operation ID). If not set, an operation ID is auto-generated from the HTTP method and path.

func WithRequestSchema

func WithRequestSchema(schema interface{}) RouteOption

WithRequestSchema sets the request schema for auto-parsing. The schema should be a struct type that defines the expected request structure.

func WithResponseSchema

func WithResponseSchema(schema interface{}) RouteOption

WithResponseSchema sets the response schema for documentation and validation. The schema should be a struct type that defines the expected response structure.

func WithTags

func WithTags(tags ...string) RouteOption

WithTags sets the route tags for API documentation. Tags help organize and categorize routes in the generated documentation.

type RouteOptions

type RouteOptions struct {
	RequestSchema  interface{}     // Struct for request parsing and validation
	ResponseSchema interface{}     // Struct for response validation and documentation
	Middleware     []fiber.Handler // Middleware handlers for the route
	Description    string          // Description for API documentation
	Tags           []string        // Tags for API documentation
	RequireJWTAuth bool            // Require HTTP Bearer (JWT) auth for this route (OpenAPI security)
	OperationID    string          // Explicit operation ID for the OpenAPI spec; falls back to an auto-generated one if empty
}

RouteOptions contains configuration for a route, such as schemas, middleware, and metadata.

type ValidationRequestError added in v0.4.4

type ValidationRequestError struct {
	Message string             `json:"error"`
	Details []FieldErrorDetail `json:"details,omitempty"`
}

ValidationRequestError is used for request validation errors

func (*ValidationRequestError) Error added in v0.4.4

func (e *ValidationRequestError) Error() string

Error implements the error interface for ValidationRequestError

type ValidationResponseError added in v0.4.4

type ValidationResponseError struct {
	Message string             `json:"error"`
	Details []FieldErrorDetail `json:"details,omitempty"`
}

ValidationResponseError is used for response validation errors

func (*ValidationResponseError) Error added in v0.4.4

func (e *ValidationResponseError) Error() string

Error implements the error interface for ValidationResponseError

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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