autofiber

package module
v0.4.9 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2025 License: MIT Imports: 9 Imported by: 0

README

AutoFiber

A FastAPI-like wrapper for the Fiber web framework in Go, providing automatic request parsing, validation, and OpenAPI/Swagger documentation generation.

Features

  • 🔄 Complete Request/Response Flow: Parse request → Validate request → Execute handler → Validate response → Return JSON
  • 🧠 Smart Parsing: Auto-detect the best source based on HTTP method (GET: path→query, POST: body→path→query)
  • 🏷️ Unified Parse Tag: Single parse tag with options like required and default
  • 🗺️ Map/Interface Parsing: Parse structs from maps, interfaces, and other data structures
  • ✅ Request Validation: Built-in validation using struct tags with go-playground/validator
  • ✅ Response Validation: Validate response data before sending to client
  • 📚 Auto Documentation: Generate OpenAPI 3.0 specification and Swagger UI
  • 🔒 Type Safety: Full type safety with Go generics
  • ⚙️ Route Options: Flexible route configuration with options pattern
  • 🔌 Middleware Integration: Seamless integration with Fiber middleware
  • 🎯 Clean Architecture: Modular design with separate concerns
  • OpenAPI Schema Naming & Generic Response:
    • Schema Naming: AutoFiber generates OpenAPI schema names that are RFC3986-compliant. For generic structs, the schema name will be in the form APIResponse_User (for APIResponse[User]). For non-generic structs, the schema name is simply the type name (e.g., LoginResponse).
    • Generic Response Support: You can use generic response wrappers for consistent API responses. Example:
      type APIResponse[T any] struct {
          Code    int    `json:"code"`
          Message string `json:"message"`
          Data    T      `json:"data"`
      }
      // Usage in route:
      app.Get("/user", handler.GetUser, autofiber.WithResponseSchema(APIResponse[User]{}))
      
    • Request Body Rules: Only POST, PUT, and PATCH methods generate a requestBody in the OpenAPI spec. GET, DELETE, HEAD, and OPTIONS never have a request body, even if a request schema is provided.

Installation

go get github.com/vuongtlt13/auto-fiber

Project Structure

auto-fiber/
  app.go            // App core: AutoFiber struct, route registration, group, listen, etc.
  group.go          // Route grouping logic
  handlers.go       // Handler creation, signature validation, Authorization checks, response validation
  parser.go         // Request parsing from multiple sources (body, query, path, ...)
  validator.go      // Response validation logic
  map_parser.go     // Parse struct from map/interface
  docs.go           // OpenAPI/Swagger documentation generation (bearerAuth, security)
  options.go        // Route option functions (WithRequestSchema, WithResponseSchema, WithJwtAuth, ...)
  types.go          // Core types, RouteOptions, ParseSource, RequireJWTAuth inference
  example/          // Example usage and demo app
  docs/             // Documentation and guides
  • app.go: Initialize app, register routes, groups, listen.
  • group.go: Support for route groups, group middleware.
  • handlers.go: Create handlers with correct signature, signature validation, Authorization enforcement (401 on missing header when JWT is required), response validation.
  • parser.go: Automatically parse requests from multiple sources (body, query, path, header, cookie).
  • validator.go: Validate response before returning to client.
  • map_parser.go: Support parsing struct from map/interface (for test, mock, ...).
  • docs.go: Generate OpenAPI spec, serve Swagger UI/docs.
  • options.go: Option functions for routes (schema, tags, description, ...).
  • types.go: Define core types, RouteOptions, ParseSource, ...

Quick Start

package main

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

// Request schema with parse tag
// (parse from path, query, header, body)
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"`
    Password string `json:"password" validate:"required,min=8"`
    Name     string `json:"name" validate:"required"`
}

type UserResponse struct {
    ID        int       `json:"id" validate:"required"`
    Email     string    `json:"email" validate:"required,email"`
    Name      string    `json:"name" validate:"required"`
    Role      string    `json:"role" validate:"required,oneof=admin user"`
    CreatedAt time.Time `json:"created_at" validate:"required"`
}

type APIResponse[T any] struct {
    Code    int    `json:"code"`
    Message string `json:"message"`
    Data    T      `json:"data"`
}

type UserHandler struct{}

// Handler signature for AutoFiber:
func (h *UserHandler) CreateUser(c *fiber.Ctx, req *CreateUserRequest) (interface{}, error) {
    user := UserResponse{
        ID:        1,
        Email:     req.Email,
        Name:      req.Name,
        Role:      req.Role,
        CreatedAt: time.Now(),
    }
    return user, nil
}

// Handler returning generic response
func (h *UserHandler) GetUser(c *fiber.Ctx) (interface{}, error) {
    user := UserResponse{
        ID:        1,
        Email:     "user@example.com",
        Name:      "John Doe",
        Role:      "user",
        CreatedAt: time.Now(),
    }
    return APIResponse[UserResponse]{Code: 0, Message: "success", Data: user}, nil
}

func main() {
    app := autofiber.NewWithOptions(
        fiber.Config{EnablePrintRoutes: true},
        autofiber.WithOpenAPI(autofiber.OpenAPIInfo{
            Title:       "AutoFiber API",
            Description: "A sample API with complete request/response flow",
            Version:     "0.3.1",
        }),
    )

    handler := &UserHandler{}

    app.Post("/organizations/:org_id/users", handler.CreateUser,
        autofiber.WithRequestSchema(CreateUserRequest{}),
        autofiber.WithResponseSchema(UserResponse{}),
        autofiber.WithDescription("Create a new user in an organization"),
        autofiber.WithTags("users", "admin"),
    )

    app.Get("/user", handler.GetUser,
        autofiber.WithResponseSchema(APIResponse[UserResponse]{}),
        autofiber.WithDescription("Get a user with generic response"),
        autofiber.WithTags("users"),
    )

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

Complete Request/Response Flow

AutoFiber provides a complete flow similar to FastAPI:

Parse Request → Validate Request → Execute Handler → Validate Response → Return JSON
Flow Details
  1. Parse Request: Automatically parse from multiple sources (body, query, path, headers, cookies)
  2. Validate Request: Validate parsed data against struct tags
  3. Execute Handler: Run your business logic
  4. Validate Response: Validate response data before sending
  5. Return JSON: Send validated response to client

Using Struct Validation Like Pydantic

AutoFiber uses go-playground/validator under the hood.
You can declare structs with validate:"..." tags and manually trigger validation, similar to Pydantic, either via the ValidateStruct helper or directly from GetValidator():

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

func main() {
    input := &UserInput{
        Email: "invalid-email",
        Age:   16,
    }

    // Option 1: use AutoFiber's generic helper
    if err := autofiber.ValidateStruct(input); err != nil {
        fmt.Printf("validation error (ValidateStruct): %+v\n", err)
    }

    // Option 2: use the global validator directly (if you need more control)
    v := autofiber.GetValidator()
    if err := v.Struct(input); err != nil {
        fmt.Printf("validation error (GetValidator): %+v\n", err)
    }
}

In a request handler, if you use:

autofiber.WithRequestSchema(MyRequest{})

AutoFiber will:

  1. Parse data into *MyRequest (body, query, path, header, cookie, form) based on tags.
  2. Call ValidateStruct(req) (or GetValidator().Struct(req)) to validate.
  3. Only execute your handler when the data is valid.
Notes about required, zero values, and nullable fields

AutoFiber follows go-playground/validator's semantics for required:

  • For value types (int, float, string, bool, structs):
    • required means the field must be non-zero for its Go type:
      • 0 for integers is considered invalid for required
      • 0.0 for floats is invalid
      • "" (empty string) is invalid
      • false for bool is invalid
  • For pointer and reference types (*T, []T, map[...]T, etc.):
    • required means the value must be non-nil.

Common patterns:

type User struct {
    // Must be present and non-empty
    Name string `json:"name" validate:"required"`

    // 0 is allowed, but you still want a lower bound
    Age int `json:"age" validate:"gte=0"`

    // "Required but nullable" for JSON:
    // - JSON must contain "nickname"
    // - value can be null or a string
    Nickname *string `json:"nickname" validate:"required"`
}

With the above:

  • {"name": "A", "age": 0, "nickname": "B"} → valid
  • {"name": "A", "age": 0, "nickname": null} → valid (field present but null)
  • {"name": "A", "age": 0} → invalid (missing required nickname)
  • {"age": 0, "nickname": "B"} → invalid (missing required name)

If you want 0 to be a valid value and enforce presence, prefer pointer types plus required or value types with range checks (e.g. gte=0) instead of required alone.

Handler Signatures

Supported Signatures for AutoFiber:

// Standard handler with request parsing: return data and error
// You can use interface{} or the concrete response schema type
func (h *Handler) CompleteHandler(c *fiber.Ctx, req *RequestSchema) (interface{}, error) {
    return ResponseSchema{...}, nil
}

// When using WithResponseSchema, prefer returning the concrete schema type for better type safety
func (h *Handler) CompleteHandlerTyped(c *fiber.Ctx, req *RequestSchema) (*ResponseSchema, error) {
    return &ResponseSchema{...}, nil
}

// Handler without request parsing: return data and error
func (h *Handler) SimpleHandler(c *fiber.Ctx) (interface{}, error) {
    return ResponseSchema{...}, nil
}

// When using WithResponseSchema, prefer returning the concrete schema type
func (h *Handler) SimpleHandlerTyped(c *fiber.Ctx) (*ResponseSchema, error) {
    return &ResponseSchema{...}, nil
}

Use only for health check or custom response:

func (h *Handler) Health(c *fiber.Ctx) error {
    return c.JSON(fiber.Map{"status": "ok"})
}

NOT supported (will cause panic):

// Do not use this signature - AutoFiber requires (interface{}, error) or (*Schema, error) return
func (h *Handler) BadHandler(c *fiber.Ctx, req *RequestSchema) error {
    return c.JSON(...)
}

Note:

  • AutoFiber supports both (interface{}, error) and (*ResponseSchema, error) return types.
  • When using WithResponseSchema, prefer returning the concrete schema type (e.g., *UserResponse) instead of interface{} for better type safety and clarity.
  • The old signature func(c *fiber.Ctx, req *T) error is no longer supported.

JWT Auth: Two Ways to Declare and Enforce Authorization

AutoFiber supports Bearer (JWT) in OpenAPI/Swagger and runtime enforcement. You can declare JWT in two ways:

  1. Route option: WithJwtAuth()

    • Adds bearerAuth security to the operation (OpenAPI) and ensures runtime checks for Authorization.
  2. Request schema: required Authorization header

    • Example field: Authorization string `parse:"header:Authorization" validate:"required"
    • applyOptions will auto-set RequireJWTAuth when it detects a required Authorization header in your schema (including embedded structs).
Runtime behavior
  • If RequireJWTAuth is true (either via WithJwtAuth or auto-inferred from schema), and the Authorization header is missing, the request returns 401 Missing Authorization header.
  • This check happens for both handlers with and without a request schema.
Example: route option (no header parsing in schema)
app.Get("/profile",
    handler.Profile,
    autofiber.WithJwtAuth(), // declares Bearer auth in docs + runtime 401 on missing Authorization
)
Example: request schema (explicit header parsing)
type ProfileRequest struct {
    Authorization string `parse:"header:Authorization" validate:"required" description:"Bearer <token>"`
}

app.Get("/profile",
    handler.ProfileWithHeaderParse,
    autofiber.WithRequestSchema(ProfileRequest{}), // auto-infers RequireJWTAuth from schema
)
What Swagger UI shows
  • Any route with JWT (either method) gets security: [{"bearerAuth": []}] and the bearerAuth scheme is added to components.securitySchemes.
  • Users can click Authorize and enter a Bearer token once; it applies to all secured routes.

HTTP Methods and Request Bodies (DELETE behavior)

AutoFiber aligns request body handling with common HTTP API practices:

  • GET, DELETE, HEAD, OPTIONS:

    • By default, no request body is generated in OpenAPI (no requestBody), even if your request schema is a struct.
    • Fields without parse tags are treated as path/query parameters only, not body.
    • If you want a body for these methods (e.g., a bulk DELETE), you must explicitly use parse:"body:..." on the fields you want in the body.
  • POST, PUT, PATCH:

    • If the request schema is a struct and you don't specify parse:"body:...", AutoFiber will:
      • Treat struct fields as coming from the body by default (unless a parse tag says otherwise).
      • Generate a requestBody in OpenAPI pointing to the struct schema.

This means:

  • DELETE /resource/:id is typically modeled with path + query only (no body).
  • Advanced patterns like DELETE /resources with a JSON body for bulk operations are supported, but require explicit parse:"body:..." tags on the relevant fields.

Documentation

Contributing

If you find any issues or want to improve the documentation:

  1. Check the existing documentation first
  2. Create an issue or pull request
  3. Follow the same format and style as existing docs
  4. Include practical examples and use cases

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.

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) 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 with automatic request parsing, validation, and documentation generation in the group. 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 (*AutoFiberGroup) Delete

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

Delete registers a DELETE route with automatic request parsing, validation, and documentation generation in the group. 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 (*AutoFiberGroup) Get

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

Get registers a GET route with automatic request parsing, validation, and documentation generation in the group. 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 (*AutoFiberGroup) Head

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

Head registers a HEAD route with automatic request parsing, validation, and documentation generation in the group. 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 (*AutoFiberGroup) Options

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

Options registers an OPTIONS route with automatic request parsing, validation, and documentation generation in the group. 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 (*AutoFiberGroup) Patch

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

Patch registers a PATCH route with automatic request parsing, validation, and documentation generation in the group. 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 (*AutoFiberGroup) Post

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

Post registers a POST route with automatic request parsing, validation, and documentation generation in the group. 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 (*AutoFiberGroup) Put

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

Put registers a PUT route with automatic request parsing, validation, and documentation generation in the group. 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 (*AutoFiberGroup) Use

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

Use adds middleware to the group. This middleware will be applied to all routes registered in this group.

type AutoFiberOption added in v0.3.0

type AutoFiberOption func(*AutoFiber)

AutoFiberOption is a function type for configuring AutoFiber options

func WithOpenAPI added in v0.3.0

func WithOpenAPI(info OpenAPIInfo) AutoFiberOption

WithOpenAPI sets the OpenAPI info for the documentation (no server info).

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 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 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() RouteOption

WithJwtAuth requires HTTP Bearer (JWT) authentication for this route (OpenAPI security).

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 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)
}

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