nova

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2025 License: MIT Imports: 42 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrMissingContentType = fmt.Errorf("missing Content-Type header")

ErrMissingContentType indicates the Content-Type header was absent.

View Source
var ErrUnsupportedContentType = fmt.Errorf("unsupported Content-Type")

ErrUnsupportedContentType indicates the Content-Type was not in the allowed list.

Functions

func CreateNewMigration

func CreateNewMigration(name string) error

CreateNewMigration creates a new migration file with a basic "up" and "down" template. The new file is named using the current Unix timestamp followed by an underscore and the provided name. The migration file is saved in the migrationsFolder and contains two sections separated by "-- migrate:up" (for the migration) and "-- migrate:down" (for the rollback).

Parameters:

name - A descriptive name for the migration (e.g., "create_users_table").

Returns an error if the file creation fails, otherwise nil.

func GetBasicAuthUser

func GetBasicAuthUser(ctx context.Context) string

GetBasicAuthUser retrieves the authenticated username from the context, if available via BasicAuthMiddleware using the default key and if configured to store it.

func GetBasicAuthUserWithKey

func GetBasicAuthUserWithKey(ctx context.Context, key contextKey) string

GetBasicAuthUserWithKey retrieves the authenticated username from the context using a specific key.

func GetCSRFToken

func GetCSRFToken(ctx context.Context) string

GetCSRFToken retrieves the CSRF token from the context, if available via CSRFMiddleware using the default key. This is the token expected in subsequent unsafe requests.

func GetCSRFTokenWithKey

func GetCSRFTokenWithKey(ctx context.Context, key contextKey) string

GetCSRFTokenWithKey retrieves the CSRF token from the context using a specific key.

func GetRealIP

func GetRealIP(ctx context.Context) string

GetRealIP retrieves the client's real IP from the context, if available via RealIPMiddleware using the default key.

func GetRealIPWithKey

func GetRealIPWithKey(ctx context.Context, key contextKey) string

GetRealIPWithKey retrieves the client's real IP from the context using a specific key.

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID retrieves the request ID from the context, if available via RequestIDMiddleware using the default key.

func GetRequestIDWithKey

func GetRequestIDWithKey(ctx context.Context, key contextKey) string

GetRequestIDWithKey retrieves the request ID from the context using a specific key.

func LoadDotenv

func LoadDotenv(paths ...string) error

LoadDotenv loads variables from a .env file, expands them, and sets them as environment variables. If no path is provided, ".env" is used. If the specified file doesn't exist, it is silently ignored.

func MigrateDown

func MigrateDown(db *sql.DB, steps int) error

MigrateDown rolls back migrations on the provided database. It reads migration files from the migrations folder, sorts them in descending order, and applies the rollback (down) statements for each migration file where the migration version is less than or equal to the current version. The parameter steps indicates how many migrations to roll back: if steps is 0 the function rolls back one migration by default.

Parameters:

db    - The database handle (from database/sql).
steps - The number of migrations to roll back (0 means 1 migration).

Returns an error if rollback fails, otherwise nil.

func MigrateUp

func MigrateUp(db *sql.DB, steps int) error

MigrateUp applies pending migrations to the provided database. It reads migration files from the migrations folder, sorts them in ascending order, and applies each migration with a version greater than the current database version. The parameter steps indicates how many migrations to apply: if steps is 0 the function applies all pending migrations.

Parameters:

db    - The database handle (from database/sql).
steps - The maximum number of migrations to apply (0 means apply all).

Returns an error if migration fails, otherwise nil.

func NewBufferingResponseWriterInterceptor

func NewBufferingResponseWriterInterceptor(w http.ResponseWriter) *bufferingResponseWriterInterceptor

NewBufferingResponseWriterInterceptor creates a new buffering interceptor.

func NewResponseWriterInterceptor

func NewResponseWriterInterceptor(w http.ResponseWriter) *responseWriterInterceptor

NewResponseWriterInterceptor creates a new interceptor.

func Serve

func Serve(ctx *Context, router http.Handler) error

Serve launches the web server (concurrently) with graceful shutdown and live reloading (if enabled). It wraps key goroutines with recovery blocks to avoid crashes due to unexpected errors. It also allows for logging customization via context options.

Types

type ActionFunc

type ActionFunc func(ctx *Context) error

ActionFunc defines the function signature for CLI actions (both global and command-specific). It receives a Context containing parsed flags and arguments.

type AuthValidator

type AuthValidator func(username, password string) bool

AuthValidator is a function type that validates the provided username and password. It returns true if the credentials are valid.

type BasicAuthConfig

type BasicAuthConfig struct {
	// Realm is the authentication realm presented to the client. Defaults to "Restricted".
	Realm string
	// Validator is the function used to validate username/password combinations. Required.
	Validator AuthValidator
	// StoreUserInContext determines whether to store the validated username in the request context.
	// Defaults to false.
	StoreUserInContext bool
	// ContextKey is the key used to store the username if StoreUserInContext is true.
	// Defaults to the package's internal basicAuthUserKey.
	ContextKey contextKey
}

BasicAuthConfig holds configuration for BasicAuthMiddleware.

type BoolFlag

type BoolFlag struct {
	// Name is the primary identifier for the flag (e.g., "verbose"). Used as --name. (Required)
	Name string
	// Aliases provide alternative names (e.g., "V"). Single letters are used as -V.
	Aliases []string
	// Usage provides a brief description of the flag's purpose for help text. (Required)
	Usage string
	// Default sets the default value. Note: Presence of the flag usually implies true.
	Default bool
	// Required is ignored for BoolFlag as presence implies the value.
	Required bool
}

BoolFlag defines a flag that acts as a boolean switch (true if present, false otherwise).

func (*BoolFlag) Apply

func (f *BoolFlag) Apply(set *flag.FlagSet, cli *CLI) error

Apply registers the bool flag with the flag.FlagSet.

func (*BoolFlag) GetAliases

func (f *BoolFlag) GetAliases() []string

GetAliases returns the aliases for the flag.

func (*BoolFlag) GetName

func (f *BoolFlag) GetName() string

GetName returns the primary name of the flag.

func (*BoolFlag) IsRequired

func (f *BoolFlag) IsRequired() bool

IsRequired always returns false for boolean flags.

func (*BoolFlag) String

func (f *BoolFlag) String() string

String returns the help text representation of the flag.

func (*BoolFlag) Validate

func (f *BoolFlag) Validate(set *flag.FlagSet) error

Validate always returns nil for boolean flags.

type CLI

type CLI struct {
	// Name of the application (Required).
	Name string
	// Version string for the application (Required). Displayed with the --version flag.
	Version string
	// Description provides a brief explanation of the application's purpose, shown in help text.
	Description string
	// Commands is a list of commands the application supports.
	Commands []*Command
	// Action is the default function to run when no command is specified.
	// If nil and no command is given, help is shown.
	Action ActionFunc
	// GlobalFlags are flags applicable to the application as a whole, before any command.
	// Flags named "version" or aliased "v" are reserved and cannot be used.
	// The "help" flag/alias is handled solely by the built-in 'help' command.
	GlobalFlags []Flag
	// Authors lists the application's authors, shown in the main help text.
	Authors string
	// contains filtered or unexported fields
}

CLI represents the command-line application structure. It holds the application's metadata, commands, global flags, and the main action. Name and Version are required fields when creating a CLI instance via NewCLI.

func NewCLI

func NewCLI(cli *CLI) (*CLI, error)

NewCLI creates and validates a new CLI application instance based on the provided configuration. The Name and Version fields in the input CLI struct are required. It checks for conflicts with reserved names/aliases (help command, h alias, version flag, v alias) and basic flag/command requirements. Returns the validated CLI instance or an error if validation fails.

func (*CLI) AddCommand

func (c *CLI) AddCommand(cmd *Command) error

AddCommand registers a new command with the application *after* initial NewCLI() validation. It performs the same conflict checks as NewCLI(). It is generally recommended to define all commands and flags within the struct passed to NewCLI().

func (*CLI) Run

func (c *CLI) Run(arguments []string) error

Run executes the CLI application based on the provided command-line arguments. Call NewCLI() to create and validate the CLI instance before calling Run. Run parses flags, handles the built-in version flag and help command, validates required flags, and executes the appropriate action (global or command-specific).

func (*CLI) ShowHelp

func (c *CLI) ShowHelp(w io.Writer)

ShowHelp prints the main help message for the application to the specified writer.

type CORSConfig

type CORSConfig struct {
	// AllowedOrigins is a list of origins that are allowed to make cross-site requests.
	// An origin of "*" allows any origin. Defaults to allowing no origins (empty list).
	AllowedOrigins []string
	// AllowedMethods is a list of HTTP methods that are allowed.
	// Defaults to "GET, POST, PUT, DELETE, PATCH, OPTIONS".
	AllowedMethods []string
	// AllowedHeaders is a list of request headers that clients are allowed to send.
	// Defaults to "Content-Type, Authorization, X-Request-ID". Use "*" to allow any header.
	AllowedHeaders []string
	// ExposedHeaders is a list of response headers that clients can access.
	// Defaults to an empty list.
	ExposedHeaders []string
	// AllowCredentials indicates whether the browser should include credentials (like cookies)
	// with the request. Cannot be used with AllowedOrigins = ["*"]. Defaults to false.
	AllowCredentials bool
	// MaxAgeSeconds specifies how long the result of a preflight request can be cached
	// in seconds. Defaults to 86400 (24 hours). A value of -1 disables caching.
	MaxAgeSeconds int
}

CORSConfig holds configuration for CORSMiddleware.

type CSRFConfig

type CSRFConfig struct {
	// Logger specifies the logger instance for errors. Defaults to log.Default().
	Logger *log.Logger
	// FieldName is the name of the form field to check for the CSRF token.
	// Defaults to "csrf_token".
	FieldName string
	// HeaderName is the name of the HTTP header to check for the CSRF token.
	// Defaults to "X-CSRF-Token".
	HeaderName string
	// CookieName is the name of the cookie used to store the CSRF secret.
	// Defaults to "_csrf". It should be HttpOnly.
	CookieName string
	// ContextKey is the key used to store the generated token in the request context.
	// Defaults to the package's internal csrfTokenKey.
	ContextKey contextKey
	// ErrorHandler is called when CSRF validation fails.
	// Defaults to sending a 403 Forbidden response.
	ErrorHandler http.HandlerFunc
	// CookiePath sets the path attribute of the CSRF cookie. Defaults to "/".
	CookiePath string
	// CookieDomain sets the domain attribute of the CSRF cookie. Defaults to "".
	CookieDomain string
	// CookieMaxAge sets the max-age attribute of the CSRF cookie.
	// Defaults to 12 hours.
	CookieMaxAge time.Duration
	// CookieSecure sets the secure attribute of the CSRF cookie.
	// Defaults to false (for HTTP testing). Set to true in production with HTTPS.
	CookieSecure bool
	// CookieSameSite sets the SameSite attribute of the CSRF cookie.
	// Defaults to http.SameSiteLaxMode.
	CookieSameSite http.SameSite
	// TokenLength is the byte length of the generated token. Defaults to 32.
	TokenLength int
	// SkipMethods is a list of HTTP methods to skip CSRF checks for.
	// Defaults to ["GET", "HEAD", "OPTIONS", "TRACE"].
	SkipMethods []string
}

CSRFConfig holds configuration for CSRFMiddleware.

type CacheControlConfig

type CacheControlConfig struct {
	// CacheControlValue is the string to set for the Cache-Control header. Required.
	// Example values: "no-store", "no-cache", "public, max-age=3600"
	CacheControlValue string
}

CacheControlConfig holds configuration for CacheControlMiddleware.

type Command

type Command struct {
	// Name is the primary identifier for the command (Required).
	Name string
	// Aliases provide alternative names for invoking the command. "h" is reserved.
	Aliases []string
	// Usage provides a short description of the command's purpose, shown in the main help list.
	Usage string
	// Description gives a more detailed explanation of the command, shown in the command's help.
	Description string
	// ArgsUsage describes the expected arguments for the command, shown in the command's help.
	// Example: "<input-file> [output-file]"
	ArgsUsage string
	// Action is the function executed when this command is invoked (Required).
	Action ActionFunc
	// Flags are the options specific to this command.
	// Flags named "help" or aliased "h" are reserved and cannot be used.
	Flags []Flag
}

Command defines a specific action the CLI application can perform. It includes metadata, flags specific to the command, and the action function. Commands named "help" or aliased "h" are reserved.

func (*Command) ShowHelp

func (cmd *Command) ShowHelp(w io.Writer, appName string)

ShowHelp prints the help message for a specific command to the specified writer.

type Components

type Components struct {
	Schemas map[string]*SchemaObject `json:"schemas,omitempty"`
}

Components holds reusable schema definitions for the OpenAPI spec.

type ConcurrencyLimiterConfig

type ConcurrencyLimiterConfig struct {
	// MaxConcurrent is the maximum number of requests allowed to be processed concurrently. Required.
	MaxConcurrent int
	// WaitTimeout is the maximum duration a request will wait for a slot before failing.
	// If zero or negative, requests wait indefinitely.
	WaitTimeout time.Duration
	// OnLimitExceeded allows custom handling when the concurrency limit is hit and timeout occurs (if set).
	// If nil, sends 503 Service Unavailable.
	OnLimitExceeded func(w http.ResponseWriter, r *http.Request)
}

ConcurrencyLimiterConfig holds configuration for ConcurrencyLimiterMiddleware.

type Context

type Context struct {
	// CLI points to the parent application instance.
	CLI *CLI
	// Command points to the specific command being executed (nil for the global action).
	Command *Command
	// contains filtered or unexported fields
}

Context provides access to parsed flags, arguments, and application/command metadata within an ActionFunc.

func (*Context) Args

func (c *Context) Args() []string

Args returns the non-flag arguments remaining after parsing for the current context.

func (*Context) Bool

func (c *Context) Bool(name string) bool

Bool returns the boolean value of a flag specified by name. It checks command flags first, then global flags. Returns false if not found or type mismatch.

func (*Context) Float64

func (c *Context) Float64(name string) float64

Float64 returns the float64 value of a flag specified by name. It checks command flags first, then global flags. Returns 0.0 if not found or type mismatch.

func (*Context) Int

func (c *Context) Int(name string) int

Int returns the integer value of a flag specified by name. It checks command flags first, then global flags. Returns 0 if not found or type mismatch.

func (*Context) String

func (c *Context) String(name string) string

String returns the string value of a flag specified by name. It checks command flags first, then global flags. Returns "" if not found or type mismatch.

func (*Context) StringSlice

func (c *Context) StringSlice(name string) []string

StringSlice returns the []string value of a flag specified by name. It checks command flags first, then global flags. Returns nil if not found or type mismatch.

type DocumentConfig

type DocumentConfig struct {
	Lang        string        // Lang attribute for `<html>` tag, defaults to "en".
	Title       string        // Content for `<title>` tag, defaults to "Document".
	Charset     string        // Charset for `<meta charset>`, defaults to "utf-8".
	Viewport    string        // Content for `<meta name="viewport">`, defaults to "width=device-width, initial-scale=1".
	Description string        // Content for `<meta name="description">`. If empty, tag is omitted.
	Keywords    string        // Content for `<meta name="keywords">`. If empty, tag is omitted.
	Author      string        // Content for `<meta name="author">`. If empty, tag is omitted.
	HeadExtras  []HTMLElement // Additional HTMLElements to be included in the `<head>` section.
}

DocumentConfig provides configuration options for creating a new HTML document. Fields left as zero-values (e.g., empty strings) will use sensible defaults or be omitted if optional (like Description, Keywords, Author).

type ETagConfig

type ETagConfig struct {
	// Weak determines if weak ETags (prefixed with W/) should be generated.
	// Weak ETags indicate semantic equivalence, not byte-for-byte identity.
	// Defaults to false (strong ETags).
	Weak bool
	// SkipNoContent determines whether to skip ETag generation/checking for
	// responses with status 204 No Content. Defaults to true.
	SkipNoContent bool
}

ETagConfig holds configuration for ETagMiddleware.

type Element

type Element struct {
	// contains filtered or unexported fields
}

Element represents an HTML element with attributes, content, and child elements. It supports both self-closing elements (like `<img>`) and container elements (like `<div>`). Elements can be chained using fluent API methods for convenient construction.

func A

func A(href string, content ...HTMLElement) *Element

A creates an `<a>` anchor element.

func Abbr

func Abbr(content ...HTMLElement) *Element

Abbr creates an `<abbr>` abbreviation element.

func Address

func Address(content ...HTMLElement) *Element

Address creates an `<address>` semantic element.

func Article

func Article(content ...HTMLElement) *Element

Article creates an `<article>` semantic element.

func Aside

func Aside(content ...HTMLElement) *Element

Aside creates an `<aside>` semantic element.

func Audio

func Audio(content ...HTMLElement) *Element

Audio creates an `<audio>` element.

func B

func B(content ...HTMLElement) *Element

B creates a `<b>` element for stylistically offset text.

func Base

func Base(href string) *Element

Base creates a `<base>` element.

func Blockquote

func Blockquote(content ...HTMLElement) *Element

Blockquote creates a `<blockquote>` element.

func Body

func Body(content ...HTMLElement) *Element

Body creates a `<body>` element.

func Br

func Br() *Element

Br creates a self-closing `<br>` line break element.

func Button

func Button(content ...HTMLElement) *Element

Button creates a `<button>` element.

func ButtonInput

func ButtonInput(valueText string) *Element

ButtonInput creates an `<input type="button">`.

func Caption

func Caption(content ...HTMLElement) *Element

Caption creates a `<caption>` element for a table.

func CheckboxInput

func CheckboxInput(name string) *Element

CheckboxInput creates an `<input type="checkbox">`.

func Cite

func Cite(content ...HTMLElement) *Element

Cite creates a `<cite>` element.

func Code

func Code(content ...HTMLElement) *Element

Code creates a `<code>` element.

func Col

func Col() *Element

Col creates a `<col>` element. It's self-closing.

func Colgroup

func Colgroup(content ...HTMLElement) *Element

Colgroup creates a `<colgroup>` element.

func ColorInput

func ColorInput(name string) *Element

ColorInput creates an `<input type="color">` field.

func Datalist

func Datalist(id string, content ...HTMLElement) *Element

Datalist creates a `<datalist>` element.

func DateInput

func DateInput(name string) *Element

DateInput creates an `<input type="date">` field.

func DateTimeLocalInput

func DateTimeLocalInput(name string) *Element

DateTimeLocalInput creates an `<input type="datetime-local">` field.

func Details

func Details(content ...HTMLElement) *Element

Details creates a `<details>` element.

func Dfn

func Dfn(content ...HTMLElement) *Element

Dfn creates a `<dfn>` definition element.

func DialogEl

func DialogEl(content ...HTMLElement) *Element

DialogEl creates a `<dialog>` element. Renamed to avoid potential conflicts.

func Div

func Div(content ...HTMLElement) *Element

Div creates a `<div>` element.

func Em

func Em(content ...HTMLElement) *Element

Em creates an `<em>` emphasis element.

func EmailInput

func EmailInput(name string) *Element

EmailInput creates an `<input type="email">` field.

func EmbedEl

func EmbedEl(src string, embedType string) *Element

EmbedEl creates an `<embed>` element. It's self-closing. Renamed to avoid keyword conflict.

func Favicon

func Favicon(href string, rel ...string) *Element

Favicon creates a `<link>` element for a favicon.

func Fieldset

func Fieldset(content ...HTMLElement) *Element

Fieldset creates a `<fieldset>` element.

func Figcaption

func Figcaption(content ...HTMLElement) *Element

Figcaption creates a `<figcaption>` element.

func Figure

func Figure(content ...HTMLElement) *Element

Figure creates a `<figure>` element.

func FileInput

func FileInput(name string) *Element

FileInput creates an `<input type="file">` field.

func Footer(content ...HTMLElement) *Element

Footer creates a `<footer>` semantic element.

func Form

func Form(content ...HTMLElement) *Element

Form creates a `<form>` element.

func H1

func H1(content ...HTMLElement) *Element

H1 creates an `<h1>` heading element.

func H2

func H2(content ...HTMLElement) *Element

H2 creates an `<h2>` heading element.

func H3

func H3(content ...HTMLElement) *Element

H3 creates an `<h3>` heading element.

func H4

func H4(content ...HTMLElement) *Element

H4 creates an `<h4>` heading element.

func H5

func H5(content ...HTMLElement) *Element

H5 creates an `<h5>` heading element.

func H6

func H6(content ...HTMLElement) *Element

H6 creates an `<h6>` heading element.

func Head(content ...HTMLElement) *Element

Head creates a `<head>` element.

func Header(content ...HTMLElement) *Element

Header creates a `<header>` semantic element.

func HiddenInput

func HiddenInput(name string, value string) *Element

HiddenInput creates an `<input type="hidden">` field.

func Hr

func Hr() *Element

Hr creates a self-closing `<hr>` horizontal rule element.

func Html

func Html(content ...HTMLElement) *Element

Html creates an `<html>` element.

func I

func I(content ...HTMLElement) *Element

I creates an `<i>` idiomatic text element.

func Iframe

func Iframe(src string) *Element

Iframe creates an `<iframe>` element.

func Image

func Image(src, alt string) *Element

Image creates an `<img>` element (alias for Img).

func Img

func Img(src, alt string) *Element

Img creates a self-closing `<img>` element.

func InlineScript

func InlineScript(scriptContent string) *Element

InlineScript creates a `<script>` element with inline JavaScript content.

func Input

func Input(inputType string) *Element

Input creates a self-closing `<input>` element.

func Kbd

func Kbd(content ...HTMLElement) *Element

Kbd creates a `<kbd>` keyboard input element.

func Label

func Label(content ...HTMLElement) *Element

Label creates a `<label>` element.

func Legend

func Legend(content ...HTMLElement) *Element

Legend creates a `<legend>` element.

func Li

func Li(content ...HTMLElement) *Element

Li creates a `<li>` list item element.

func Link(href, textContent string) *Element

Link creates an `<a>` anchor element with href and text content.

func LinkTag

func LinkTag() *Element

LinkTag creates a generic `<link>` element. It's self-closing.

func Main

func Main(content ...HTMLElement) *Element

Main creates a `<main>` semantic element.

func Mark

func Mark(content ...HTMLElement) *Element

Mark creates a `<mark>` element.

func Meta

func Meta() *Element

Meta creates a generic `<meta>` element. It's self-closing.

func MetaCharset

func MetaCharset(charset string) *Element

MetaCharset creates a `<meta charset="...">` element.

func MetaNameContent

func MetaNameContent(name, contentVal string) *Element

MetaNameContent creates a `<meta name="..." content="...">` element.

func MetaPropertyContent

func MetaPropertyContent(property, contentVal string) *Element

MetaPropertyContent creates a `<meta property="..." content="...">` element.

func MetaViewport

func MetaViewport(contentVal string) *Element

MetaViewport creates a `<meta name="viewport" content="...">` element.

func MeterEl

func MeterEl(content ...HTMLElement) *Element

MeterEl creates a `<meter>` element. Renamed to avoid potential conflicts.

func MonthInput

func MonthInput(name string) *Element

MonthInput creates an `<input type="month">` field.

func Nav(content ...HTMLElement) *Element

Nav creates a `<nav>` semantic element.

func NoScript

func NoScript(content ...HTMLElement) *Element

NoScript creates a `<noscript>` element.

func NumberInput

func NumberInput(name string) *Element

NumberInput creates an `<input type="number">` field.

func ObjectEl

func ObjectEl(content ...HTMLElement) *Element

ObjectEl creates an `<object>` element. Renamed to avoid keyword conflict.

func Ol

func Ol(content ...HTMLElement) *Element

Ol creates an `<ol>` ordered list element.

func Optgroup

func Optgroup(label string, content ...HTMLElement) *Element

Optgroup creates an `<optgroup>` element.

func Option

func Option(value string, content ...HTMLElement) *Element

Option creates an `<option>` element.

func OutputEl

func OutputEl(content ...HTMLElement) *Element

OutputEl creates an `<output>` element. Renamed to avoid potential conflicts.

func P

func P(content ...HTMLElement) *Element

P creates a `<p>` paragraph element.

func Param

func Param(name, value string) *Element

Param creates a `<param>` element. It's self-closing.

func PasswordInput

func PasswordInput(name string) *Element

PasswordInput creates an `<input type="password">` field.

func Pre

func Pre(content ...HTMLElement) *Element

Pre creates a `<pre>` element.

func Preload

func Preload(href string, asType string) *Element

Preload creates a `<link rel="preload">` element.

func ProgressEl

func ProgressEl(content ...HTMLElement) *Element

ProgressEl creates a `<progress>` element. Renamed to avoid potential conflicts.

func Q

func Q(content ...HTMLElement) *Element

Q creates a `<q>` inline quotation element.

func RadioInput

func RadioInput(name, value string) *Element

RadioInput creates an `<input type="radio">`.

func RangeInput

func RangeInput(name string) *Element

RangeInput creates an `<input type="range">` field.

func ResetButton

func ResetButton(text string) *Element

ResetButton creates a `<button type="reset">`.

func Samp

func Samp(content ...HTMLElement) *Element

Samp creates a `<samp>` sample output element.

func Script

func Script(src string) *Element

Script creates a `<script>` element for external JavaScript files.

func SearchInput

func SearchInput(name string) *Element

SearchInput creates an `<input type="search">` field.

func Section

func Section(content ...HTMLElement) *Element

Section creates a `<section>` semantic element.

func Select

func Select(content ...HTMLElement) *Element

Select creates a `<select>` dropdown element.

func Small

func Small(content ...HTMLElement) *Element

Small creates a `<small>` element.

func Source

func Source(src string, mediaType string) *Element

Source creates a `<source>` element. It's self-closing.

func Span

func Span(content ...HTMLElement) *Element

Span creates a `<span>` inline element.

func Strong

func Strong(content ...HTMLElement) *Element

Strong creates a `<strong>` element.

func StyleSheet

func StyleSheet(href string) *Element

StyleSheet creates a `<link rel="stylesheet">` element.

func StyleTag

func StyleTag(cssContent string) *Element

StyleTag creates a `<style>` element for embedding CSS.

func Sub

func Sub(content ...HTMLElement) *Element

Sub creates a `<sub>` subscript element.

func SubmitButton

func SubmitButton(text string) *Element

SubmitButton creates a `<button type="submit">`.

func Summary

func Summary(content ...HTMLElement) *Element

Summary creates a `<summary>` element.

func Sup

func Sup(content ...HTMLElement) *Element

Sup creates a `<sup>` superscript element.

func Table

func Table(content ...HTMLElement) *Element

Table creates a `<table>` element.

func Tbody

func Tbody(content ...HTMLElement) *Element

Tbody creates a `<tbody>` table body group element.

func Td

func Td(content ...HTMLElement) *Element

Td creates a `<td>` table data cell element.

func TelInput

func TelInput(name string) *Element

TelInput creates an `<input type="tel">` field.

func TextInput

func TextInput(name string) *Element

TextInput creates an `<input type="text">` field.

func Textarea

func Textarea(content ...HTMLElement) *Element

Textarea creates a `<textarea>` element.

func Th

func Th(content ...HTMLElement) *Element

Th creates a `<th>` table header cell element.

func Thead

func Thead(content ...HTMLElement) *Element

Thead creates a `<thead>` table header group element.

func TimeEl

func TimeEl(content ...HTMLElement) *Element

TimeEl creates a `<time>` element. Renamed to avoid potential conflicts.

func TimeInput

func TimeInput(name string) *Element

TimeInput creates an `<input type="time">` field.

func TitleEl

func TitleEl(titleText string) *Element

TitleEl creates a `<title>` element with the specified text. Renamed from Title to TitleEl to avoid conflict with (*Element).Title method if it existed.

func Tr

func Tr(content ...HTMLElement) *Element

Tr creates a `<tr>` table row element.

func Track

func Track(kind, src, srclang string) *Element

Track creates a `<track>` element. It's self-closing.

func U

func U(content ...HTMLElement) *Element

U creates a `<u>` unarticulated annotation element.

func Ul

func Ul(content ...HTMLElement) *Element

Ul creates a `<ul>` unordered list element.

func UrlInput

func UrlInput(name string) *Element

UrlInput creates an `<input type="url">` field.

func VarEl

func VarEl(content ...HTMLElement) *Element

VarEl creates a `<var>` variable element. Renamed to avoid keyword conflict.

func Video

func Video(content ...HTMLElement) *Element

Video creates a `<video>` element.

func Wbr

func Wbr() *Element

Wbr creates a `<wbr>` word break opportunity element. It's self-closing.

func WeekInput

func WeekInput(name string) *Element

WeekInput creates an `<input type="week">` field.

func (*Element) Add

func (e *Element) Add(children ...HTMLElement) *Element

Add appends child elements to this element.

func (*Element) Attr

func (e *Element) Attr(key, value string) *Element

Attr sets an attribute on the element and returns the element for method chaining.

func (*Element) BoolAttr

func (e *Element) BoolAttr(key string, present bool) *Element

BoolAttr sets or removes a boolean attribute on the element. If present is true, the attribute is added (e.g., `<input disabled>`). If present is false, the attribute is removed if it exists.

func (*Element) Class

func (e *Element) Class(class string) *Element

Class sets the class attribute on the element.

func (*Element) ID

func (e *Element) ID(id string) *Element

ID sets the id attribute on the element.

func (*Element) Render

func (e *Element) Render() string

Render converts the element to its HTML string representation. It handles both self-closing and container elements, attributes, content, and children. The output is properly formatted HTML that can be sent to browsers. Content and attribute values are HTML-escaped to prevent XSS, except for specific tags like `<script>` and `<style>` whose content must be raw.

func (*Element) Style

func (e *Element) Style(style string) *Element

Style sets the style attribute on the element.

func (*Element) Text

func (e *Element) Text(text string) *Element

Text sets the text content of the element. This content is HTML-escaped during rendering.

type EnforceContentTypeConfig

type EnforceContentTypeConfig struct {
	// AllowedTypes is a list of allowed Content-Type values (e.g., "application/json").
	// The check ignores parameters like "; charset=utf-8". Required.
	AllowedTypes []string
	// MethodsToCheck specifies which HTTP methods should have their Content-Type checked.
	// Defaults to POST, PUT, PATCH.
	MethodsToCheck []string
	// OnError allows custom handling when the Content-Type is missing or unsupported.
	// If nil, sends 400 Bad Request or 415 Unsupported Media Type.
	OnError func(w http.ResponseWriter, r *http.Request, err error)
}

EnforceContentTypeConfig holds configuration for EnforceContentTypeMiddleware.

type Flag

type Flag interface {
	fmt.Stringer // For generating help text representation.

	// Apply binds the flag definition to a standard Go flag.FlagSet.
	// It configures the flag's name, aliases, usage, and default value.
	Apply(set *flag.FlagSet, cli *CLI) error
	// GetName returns the primary name of the flag (e.g., "config").
	GetName() string
	// IsRequired indicates whether the flag must be provided by the user.
	IsRequired() bool
	// Validate checks if a required flag was provided correctly after parsing.
	Validate(set *flag.FlagSet) error
	// GetAliases returns the alternative names for the flag.
	GetAliases() []string
}

Flag defines the interface for command-line flags. Concrete types like StringFlag, IntFlag, BoolFlag implement this interface.

type Float64Flag

type Float64Flag struct {
	// Name is the primary identifier for the flag (e.g., "rate"). Used as --name. (Required)
	Name string
	// Aliases provide alternative names (e.g., "r"). Single letters are used as -r.
	Aliases []string
	// Usage provides a brief description of the flag's purpose for help text. (Required)
	Usage string
	// Default sets the default value if the flag is not provided.
	Default float64
	// Required indicates if the user must provide this flag.
	Required bool
}

Float64Flag defines a flag that accepts a float64 value.

func (*Float64Flag) Apply

func (f *Float64Flag) Apply(set *flag.FlagSet, cli *CLI) error

Apply registers the float64 flag with the flag.FlagSet.

func (*Float64Flag) GetAliases

func (f *Float64Flag) GetAliases() []string

GetAliases returns the aliases for the flag.

func (*Float64Flag) GetName

func (f *Float64Flag) GetName() string

GetName returns the primary name of the flag.

func (*Float64Flag) IsRequired

func (f *Float64Flag) IsRequired() bool

IsRequired returns true if the flag must be provided.

func (*Float64Flag) String

func (f *Float64Flag) String() string

String returns the help text representation of the flag.

func (*Float64Flag) Validate

func (f *Float64Flag) Validate(set *flag.FlagSet) error

Validate checks if the required flag was provided.

type ForceHTTPSConfig

type ForceHTTPSConfig struct {
	// TargetHost overrides the host used in the redirect URL. If empty, uses r.Host.
	TargetHost string
	// TargetPort overrides the port used in the redirect URL. If 0, omits the port (standard 443).
	TargetPort int
	// RedirectCode is the HTTP status code for redirection. Defaults to http.StatusMovedPermanently (301).
	RedirectCode int
	// ForwardedProtoHeader is the header name to check for the original protocol (e.g., "X-Forwarded-Proto").
	// Defaults to "X-Forwarded-Proto".
	ForwardedProtoHeader string
	// TrustForwardedHeader explicitly enables trusting the ForwardedProtoHeader. Defaults to true.
	// Set to false if your proxy setup doesn't reliably set this header.
	TrustForwardedHeader *bool // Use pointer for explicit false vs unset
}

ForceHTTPSConfig holds configuration for ForceHTTPSMiddleware.

type Group

type Group struct {
	// contains filtered or unexported fields
}

Group is a lightweight helper that allows users to register a set of routes that share a common prefix and/or middleware. It delegates to the parent router while applying its own prefix and middleware chain.

func (*Group) Delete

func (g *Group) Delete(pattern string, handler http.HandlerFunc, options ...*RouteOptions)

Delete registers a new route for HTTP DELETE requests within the group.

func (*Group) DeleteFunc

func (g *Group) DeleteFunc(pattern string, handler HandlerFunc, options ...*RouteOptions)

DeleteFunc registers a new enhanced route for HTTP DELETE requests within the group.

func (*Group) Get

func (g *Group) Get(pattern string, handler http.HandlerFunc, options ...*RouteOptions)

Get registers a new route for HTTP GET requests within the group.

func (*Group) GetFunc

func (g *Group) GetFunc(pattern string, handler HandlerFunc, options ...*RouteOptions)

GetFunc registers a new enhanced route for HTTP GET requests within the group.

func (*Group) Handle

func (g *Group) Handle(method, pattern string, handler http.HandlerFunc, opts ...*RouteOptions)

Handle registers a new route within the group, applying the group's prefix and middleware. The route is ultimately registered with the parent router after transformations.

func (*Group) HandleFunc

func (g *Group) HandleFunc(method, pattern string, handler HandlerFunc, opts ...*RouteOptions)

HandleFunc registers a new enhanced route within the group, applying the group's prefix and middleware. Uses the enhanced handler signature for better error handling.

func (*Group) Patch

func (g *Group) Patch(pattern string, handler http.HandlerFunc, options ...*RouteOptions)

Patch registers a new route for HTTP PATCH requests within the group.

func (*Group) PatchFunc

func (g *Group) PatchFunc(pattern string, handler HandlerFunc, options ...*RouteOptions)

PatchFunc registers a new enhanced route for HTTP PATCH requests within the group.

func (*Group) Post

func (g *Group) Post(pattern string, handler http.HandlerFunc, options ...*RouteOptions)

Post registers a new route for HTTP POST requests within the group.

func (*Group) PostFunc

func (g *Group) PostFunc(pattern string, handler HandlerFunc, options ...*RouteOptions)

PostFunc registers a new enhanced route for HTTP POST requests within the group.

func (*Group) Put

func (g *Group) Put(pattern string, handler http.HandlerFunc, options ...*RouteOptions)

Put registers a new route for HTTP PUT requests within the group.

func (*Group) PutFunc

func (g *Group) PutFunc(pattern string, handler HandlerFunc, options ...*RouteOptions)

PutFunc registers a new enhanced route for HTTP PUT requests within the group.

func (*Group) Use

func (g *Group) Use(mws ...Middleware)

Use adds middleware functions to the group. These middleware functions apply only to routes registered through the group, not to the parent router.

type GzipConfig

type GzipConfig struct {
	// CompressionLevel specifies the gzip compression level.
	// Accepts values from gzip.BestSpeed (1) to gzip.BestCompression (9).
	// Defaults to gzip.DefaultCompression (-1).
	CompressionLevel int
	// AddVaryHeader indicates whether to add the "Vary: Accept-Encoding" header.
	// A nil value defaults to true. Set explicitly to false to disable.
	// Disabling is only recommended if caching behavior is fully understood.
	AddVaryHeader *bool
	// Logger specifies an optional logger for errors.
	// Defaults to log.Default().
	Logger *log.Logger
	// Pool specifies an optional sync.Pool for gzip.Writer reuse.
	// Can improve performance by reducing allocations.
	Pool *sync.Pool // Optional: Pool for gzip.Writers
}

GzipConfig holds configuration options for the GzipMiddleware.

type HTMLDocument

type HTMLDocument struct {
	// contains filtered or unexported fields
}

HTMLDocument represents a full HTML document, including the DOCTYPE. Its Render method produces the complete HTML string.

func Document

func Document(config DocumentConfig, bodyContent ...HTMLElement) *HTMLDocument

Document creates a complete HTML5 document structure, encapsulated in an HTMLDocument. The returned HTMLDocument's Render method will produce the full HTML string, including the DOCTYPE.

It uses DocumentConfig to customize the document's head and html attributes, and accepts variadic arguments for the body content. Sensible defaults are applied for common attributes and meta tags if not specified in the config.

func (*HTMLDocument) Render

func (d *HTMLDocument) Render() string

Render converts the HTMLDocument to its full string representation, prepending the HTML5 DOCTYPE declaration.

type HTMLElement

type HTMLElement interface {
	Render() string
}

HTMLElement represents any HTML element that can be rendered to a string. This interface allows for composition of complex HTML structures using both predefined elements and custom implementations.

func Text

func Text(text string) HTMLElement

Text creates a raw text node.

type HandlerFunc

type HandlerFunc func(*ResponseContext) error

HandlerFunc is an enhanced handler function that receives a ResponseContext and returns an error. This allows for cleaner error handling and response management compared to standard http.HandlerFunc.

type HeaderObject

type HeaderObject struct {
	Description string        `json:"description,omitempty"`
	Schema      *SchemaObject `json:"schema"`
}

HeaderObject describes a response header in an Operation.

type HealthCheckConfig

type HealthCheckConfig struct {
	// Path is the URL path for the health check endpoint. Defaults to "/healthz".
	Path string
	// Handler is the handler function to execute for the health check.
	// If nil, a default handler returning 200 OK with "OK" body is used.
	// You can provide a custom handler to check database connections, etc.
	Handler http.HandlerFunc
}

HealthCheckConfig holds configuration for HealthCheckMiddleware.

type IPFilterConfig

type IPFilterConfig struct {
	// AllowedIPs is a list of allowed IPs or CIDRs.
	AllowedIPs []string
	// BlockedIPs is a list of blocked IPs or CIDRs. Takes precedence over AllowedIPs.
	BlockedIPs []string
	// BlockByDefault determines the behavior if an IP matches neither list.
	// If true, the IP is blocked unless explicitly in AllowedIPs (and not in BlockedIPs).
	// If false, the IP is allowed unless explicitly in BlockedIPs. Defaults to false.
	BlockByDefault bool
	// OnForbidden allows custom handling when an IP is forbidden.
	// If nil, sends 403 Forbidden.
	OnForbidden func(w http.ResponseWriter, r *http.Request)
	// Logger for potential IP parsing errors. Defaults to log.Default().
	Logger *log.Logger
}

IPFilterConfig holds configuration for IP filtering.

type Info

type Info struct {
	Title       string `json:"title"`
	Version     string `json:"version"`
	Description string `json:"description,omitempty"`
}

Info provides metadata about the API: title, version, and optional description.

type IntFlag

type IntFlag struct {
	// Name is the primary identifier for the flag (e.g., "port"). Used as --name. (Required)
	Name string
	// Aliases provide alternative names (e.g., "p"). Single letters are used as -p.
	Aliases []string
	// Usage provides a brief description of the flag's purpose for help text. (Required)
	Usage string
	// Default sets the default value if the flag is not provided.
	Default int
	// Required indicates if the user must provide this flag.
	Required bool
}

IntFlag defines a flag that accepts an integer value.

func (*IntFlag) Apply

func (f *IntFlag) Apply(set *flag.FlagSet, cli *CLI) error

Apply registers the int flag with the flag.FlagSet.

func (*IntFlag) GetAliases

func (f *IntFlag) GetAliases() []string

GetAliases returns the aliases for the flag.

func (*IntFlag) GetName

func (f *IntFlag) GetName() string

GetName returns the primary name of the flag.

func (*IntFlag) IsRequired

func (f *IntFlag) IsRequired() bool

IsRequired returns true if the flag must be provided.

func (*IntFlag) String

func (f *IntFlag) String() string

String returns the help text representation of the flag.

func (*IntFlag) Validate

func (f *IntFlag) Validate(set *flag.FlagSet) error

Validate checks if the required flag was provided.

type LoggingConfig

type LoggingConfig struct {
	// Logger specifies the logger instance to use. Defaults to log.Default().
	Logger *log.Logger
	// LogRequestID determines whether to include the request ID (if available)
	// in log messages. Defaults to true.
	LogRequestID bool
	// RequestIDKey is the context key used to retrieve the request ID.
	// Defaults to the package's internal requestIDKey.
	RequestIDKey contextKey
}

LoggingConfig holds configuration for LoggingMiddleware.

type MaintenanceModeConfig

type MaintenanceModeConfig struct {
	// EnabledFlag is a pointer to an atomic boolean. If true, maintenance mode is active. Required.
	EnabledFlag *atomic.Bool
	// AllowedIPs is a list of IPs or CIDRs that can bypass maintenance mode.
	AllowedIPs []string
	// StatusCode is the HTTP status code returned during maintenance. Defaults to 503.
	StatusCode int
	// RetryAfterSeconds sets the Retry-After header value in seconds. Defaults to 300.
	RetryAfterSeconds int
	// Message is the response body sent during maintenance. Defaults to a standard message.
	Message string
	// Logger for potential IP parsing errors. Defaults to log.Default().
	Logger *log.Logger
}

MaintenanceModeConfig holds configuration for MaintenanceModeMiddleware.

type MaxRequestBodySizeConfig

type MaxRequestBodySizeConfig struct {
	// LimitBytes is the maximum allowed size of the request body in bytes. Required.
	LimitBytes int64
	// OnError allows custom handling when the body size limit is exceeded.
	// If nil, sends 413 Request Entity Too Large.
	OnError func(w http.ResponseWriter, r *http.Request)
}

MaxRequestBodySizeConfig holds configuration for MaxRequestBodySizeMiddleware.

type MediaTypeObject

type MediaTypeObject struct {
	Schema *SchemaObject `json:"schema,omitempty"`
}

MediaTypeObject holds the schema defining the media type for a request or response.

type MethodOverrideConfig

type MethodOverrideConfig struct {
	// HeaderName is the name of the header checked for the method override value.
	// Defaults to "X-HTTP-Method-Override".
	HeaderName string
	// FormFieldName is the name of the form field (used for POST requests)
	// checked for the method override value if the header is not present.
	// Set to "" to disable form field checking. Defaults to "_method".
	FormFieldName string
}

MethodOverrideConfig holds configuration for MethodOverrideMiddleware.

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware defines the function signature for middleware. A middleware is a function that wraps an http.Handler, adding extra behavior such as logging, authentication, or request modification.

func BasicAuthMiddleware

func BasicAuthMiddleware(config BasicAuthConfig) Middleware

BasicAuthMiddleware provides simple HTTP Basic Authentication.

func CORSMiddleware

func CORSMiddleware(config CORSConfig) Middleware

CORSMiddleware sets Cross-Origin Resource Sharing headers.

func CSRFMiddleware

func CSRFMiddleware(config *CSRFConfig) Middleware

CSRFMiddleware provides Cross-Site Request Forgery protection. It uses the "Double Submit Cookie" pattern. A random token is generated and set in a secure, HttpOnly cookie. For unsafe methods (POST, PUT, etc.), the middleware expects the same token to be present in a request header (e.g., X-CSRF-Token) or form field, sent by the frontend JavaScript.

func CacheControlMiddleware

func CacheControlMiddleware(config CacheControlConfig) Middleware

CacheControlMiddleware sets the Cache-Control header for responses.

func ConcurrencyLimiterMiddleware

func ConcurrencyLimiterMiddleware(config ConcurrencyLimiterConfig) Middleware

ConcurrencyLimiterMiddleware limits the number of concurrent requests.

func ETagMiddleware

func ETagMiddleware(config *ETagConfig) Middleware

ETagMiddleware adds ETag headers to responses and handles If-None-Match conditional requests, potentially returning a 304 Not Modified status. Note: This middleware buffers the entire response body in memory to calculate the ETag hash. This may be inefficient for very large responses.

func EnforceContentTypeMiddleware

func EnforceContentTypeMiddleware(config EnforceContentTypeConfig) Middleware

EnforceContentTypeMiddleware checks if the request's Content-Type header is allowed.

func ForceHTTPSMiddleware

func ForceHTTPSMiddleware(config ForceHTTPSConfig) Middleware

ForceHTTPSMiddleware redirects HTTP requests to HTTPS.

func GzipMiddleware

func GzipMiddleware(config *GzipConfig) Middleware

GzipMiddleware returns middleware that compresses response bodies using gzip if the client indicates support via the Accept-Encoding header.

func HealthCheckMiddleware

func HealthCheckMiddleware(config *HealthCheckConfig) Middleware

HealthCheckMiddleware provides a simple health check endpoint.

func IPFilterMiddleware

func IPFilterMiddleware(config IPFilterConfig) Middleware

IPFilterMiddleware restricts access based on client IP address.

func LoggingMiddleware

func LoggingMiddleware(config *LoggingConfig) Middleware

LoggingMiddleware logs request details including method, path, status, size, and duration.

func MaintenanceModeMiddleware

func MaintenanceModeMiddleware(config MaintenanceModeConfig) Middleware

MaintenanceModeMiddleware returns a 503 Service Unavailable if enabled, allowing bypass for specific IPs.

func MaxRequestBodySizeMiddleware

func MaxRequestBodySizeMiddleware(config MaxRequestBodySizeConfig) Middleware

MaxRequestBodySizeMiddleware limits the size of incoming request bodies.

func MethodOverrideMiddleware

func MethodOverrideMiddleware(config *MethodOverrideConfig) Middleware

MethodOverrideMiddleware checks a header or form field to override the request method.

func RateLimitMiddleware

func RateLimitMiddleware(config RateLimiterConfig) Middleware

RateLimitMiddleware provides basic in-memory rate limiting. Warning: This simple implementation has limitations: - Memory usage can grow indefinitely without CleanupInterval set. - Not suitable for distributed systems (limit is per instance). - Accuracy decreases slightly under very high concurrency due to locking.

func RealIPMiddleware

func RealIPMiddleware(config RealIPConfig) Middleware

RealIPMiddleware extracts the client's real IP address from proxy headers. Warning: Only use this if you have a trusted proxy setting these headers correctly.

func RecoveryMiddleware

func RecoveryMiddleware(config *RecoveryConfig) Middleware

RecoveryMiddleware recovers from panics in downstream handlers.

func RequestIDMiddleware

func RequestIDMiddleware(config *RequestIDConfig) Middleware

RequestIDMiddleware retrieves a request ID from a header or generates one. It sets the ID in the response header and request context.

func SecurityHeadersMiddleware

func SecurityHeadersMiddleware(config SecurityHeadersConfig) Middleware

SecurityHeadersMiddleware sets common security headers.

func TimeoutMiddleware

func TimeoutMiddleware(config TimeoutConfig) Middleware

TimeoutMiddleware sets a maximum duration for handling requests.

func TrailingSlashRedirectMiddleware

func TrailingSlashRedirectMiddleware(config TrailingSlashRedirectConfig) Middleware

TrailingSlashRedirectMiddleware redirects requests to add or remove a trailing slash.

type OpenAPI

type OpenAPI struct {
	OpenAPI    string               `json:"openapi"`
	Info       Info                 `json:"info"`
	Paths      map[string]*PathItem `json:"paths"`
	Components *Components          `json:"components,omitempty"`
}

OpenAPI is the root document object for an OpenAPI 3 specification.

func GenerateOpenAPISpec

func GenerateOpenAPISpec(router *Router, config OpenAPIConfig) *OpenAPI

GenerateOpenAPISpec constructs an OpenAPI 3.0 specification from the given router and configuration, including paths, operations, and components.

type OpenAPIConfig

type OpenAPIConfig struct {
	Title       string
	Version     string
	Description string
}

OpenAPIConfig holds metadata for generating an OpenAPI specification.

type Operation

type Operation struct {
	Tags        []string                   `json:"tags,omitempty"`
	Summary     string                     `json:"summary,omitempty"`
	Description string                     `json:"description,omitempty"`
	OperationID string                     `json:"operationId,omitempty"`
	Parameters  []ParameterObject          `json:"parameters,omitempty"`
	RequestBody *RequestBodyObject         `json:"requestBody,omitempty"`
	Responses   map[string]*ResponseObject `json:"responses"`
	Deprecated  bool                       `json:"deprecated,omitempty"`
}

Operation describes a single API operation on a path.

type ParameterObject

type ParameterObject struct {
	Name        string        `json:"name"`
	In          string        `json:"in"`
	Description string        `json:"description,omitempty"`
	Required    bool          `json:"required"`
	Deprecated  bool          `json:"deprecated,omitempty"`
	Schema      *SchemaObject `json:"schema"`
	Example     any           `json:"example,omitempty"`
}

ParameterObject describes a single parameter for an Operation or PathItem.

type ParameterOption

type ParameterOption struct {
	Name        string
	In          string
	Description string
	Required    bool
	Schema      any
	Example     any
}

ParameterOption configures an Operation parameter. Name and In ("query", "header", "path", "cookie") are required. Required, Schema and Example further customize the generated parameter.

type PathItem

type PathItem struct {
	Get         *Operation        `json:"get,omitempty"`
	Post        *Operation        `json:"post,omitempty"`
	Put         *Operation        `json:"put,omitempty"`
	Delete      *Operation        `json:"delete,omitempty"`
	Patch       *Operation        `json:"patch,omitempty"`
	Parameters  []ParameterObject `json:"parameters,omitempty"`
	Summary     string            `json:"summary,omitempty"`
	Description string            `json:"description,omitempty"`
}

PathItem describes the operations available on a single API path. One of Get, Post, Put, Delete, Patch may be non-nil.

type RateLimiterConfig

type RateLimiterConfig struct {
	// Requests is the maximum number of requests allowed within the Duration. Required.
	Requests int
	// Duration specifies the time window for the request limit. Required.
	Duration time.Duration
	// Burst allows temporary bursts exceeding the rate limit, up to this many requests.
	// Defaults to the value of Requests (no extra burst capacity).
	Burst int
	// KeyFunc extracts a unique key from the request to identify the client.
	// Defaults to using the client's IP address (r.RemoteAddr).
	KeyFunc func(r *http.Request) string
	// OnLimitExceeded allows custom handling when the rate limit is hit.
	// If nil, sends 429 Too Many Requests.
	OnLimitExceeded func(w http.ResponseWriter, r *http.Request)
	// CleanupInterval specifies how often to scan and remove old entries from memory.
	// If zero or negative, no automatic cleanup occurs (potential memory leak).
	// A value like 10*time.Minute is reasonable.
	CleanupInterval time.Duration
	// Logger for potential errors during key extraction or IP parsing. Defaults to log.Default().
	Logger *log.Logger
}

RateLimiterConfig holds configuration for the simple rate limiter.

type RealIPConfig

type RealIPConfig struct {
	// TrustedProxyCIDRs is a list of CIDR notations for trusted proxies.
	// If the direct connection (r.RemoteAddr) is from one of these, proxy headers are trusted.
	TrustedProxyCIDRs []string
	// IPHeaders is an ordered list of header names to check for the client's IP.
	// The first non-empty, valid IP found is used.
	// Defaults to ["X-Forwarded-For", "X-Real-IP"].
	IPHeaders []string
	// StoreInContext determines whether to store the found real IP in the request context.
	// Defaults to true.
	StoreInContext bool
	// ContextKey is the key used if StoreInContext is true. Defaults to realIPKey.
	ContextKey contextKey
}

RealIPConfig holds configuration for RealIPMiddleware.

type RecoveryConfig

type RecoveryConfig struct {
	// Logger specifies the logger instance for panic messages. Defaults to log.Default().
	Logger *log.Logger
	// LogRequestID determines whether to include the request ID (if available)
	// in log messages. Defaults to true.
	LogRequestID bool
	// RequestIDKey is the context key used to retrieve the request ID.
	// Defaults to the package's internal requestIDKey.
	RequestIDKey contextKey
	// RecoveryHandler allows custom logic to run after a panic is recovered.
	// It receives the response writer, request, and the recovered panic value.
	// If nil, a default 500 Internal Server Error response is sent.
	RecoveryHandler func(http.ResponseWriter, *http.Request, any)
}

RecoveryConfig holds configuration for RecoveryMiddleware.

type RequestBodyObject

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

RequestBodyObject describes a request body for an Operation.

type RequestIDConfig

type RequestIDConfig struct {
	// HeaderName is the name of the HTTP header to check for an existing ID
	// and to set in the response. Defaults to "X-Request-ID".
	HeaderName string
	// ContextKey is the key used to store the request ID in the request context.
	// Defaults to the package's internal requestIDKey.
	ContextKey contextKey
	// Generator is a function that generates a new request ID if one is not
	// found in the header. Defaults to a nanosecond timestamp-based generator.
	// Consider using a UUID library if external dependencies are acceptable.
	Generator func() string
}

RequestIDConfig holds configuration for RequestIDMiddleware.

type ResponseContext

type ResponseContext struct {
	// contains filtered or unexported fields
}

ResponseContext provides helper methods for sending HTTP responses with reduced boilerplate. It wraps the http.ResponseWriter and http.Request along with router context to provide convenient methods for JSON, HTML, text responses, and automatic data binding.

func (*ResponseContext) Bind

func (rc *ResponseContext) Bind(v any) error

Bind automatically unmarshals and validates request data into the provided struct. It supports both JSON and form data, with automatic content-type detection. The struct should be a pointer. Validation is performed if validation middleware is active.

func (*ResponseContext) BindForm

func (rc *ResponseContext) BindForm(v any) error

BindForm binds form data into the provided struct using reflection. The struct should be a pointer. Field names are matched using JSON tags or struct field names. Supports string, bool, int, and float fields with automatic type conversion.

func (*ResponseContext) BindJSON

func (rc *ResponseContext) BindJSON(v any) error

BindJSON unmarshals JSON request body into the provided struct. The struct should be a pointer. Returns an error if the body is nil or JSON is invalid.

func (*ResponseContext) BindValidated

func (rc *ResponseContext) BindValidated(v any) error

BindValidated binds and validates request data (JSON or form) with comprehensive validation.

func (*ResponseContext) HTML

func (rc *ResponseContext) HTML(statusCode int, content HTMLElement) error

HTML sends an HTML response with the given status code and content. It automatically sets the Content-Type header to "text/html; charset=utf-8" and renders the provided HTMLElement to string.

func (*ResponseContext) JSON

func (rc *ResponseContext) JSON(statusCode int, data any) error

JSON sends a JSON response with the given status code and data. It automatically sets the Content-Type header to "application/json" and handles JSON encoding. Returns an error if encoding fails.

func (*ResponseContext) JSONError

func (rc *ResponseContext) JSONError(statusCode int, message string) error

JSONError sends a JSON error response with the given status code and message. It creates a standardized error response format with an "error" field.

func (*ResponseContext) Redirect

func (rc *ResponseContext) Redirect(statusCode int, url string) error

Redirect sends an HTTP redirect response with the given status code and URL. Common status codes are 301 (permanent), 302 (temporary), and 307 (temporary, preserve method).

func (*ResponseContext) Request

func (rc *ResponseContext) Request() *http.Request

Request returns the underlying http.Request for advanced request handling when the ResponseContext helpers are not sufficient.

func (*ResponseContext) Text

func (rc *ResponseContext) Text(statusCode int, text string) error

Text sends a plain text response with the given status code and text content. It automatically sets the Content-Type header to "text/plain; charset=utf-8".

func (*ResponseContext) URLParam

func (rc *ResponseContext) URLParam(key string) string

URLParam retrieves the URL parameter for the given key from the request context. Returns an empty string if the parameter is not present or if the request doesn't contain URL parameters.

func (*ResponseContext) WantsJSON

func (rc *ResponseContext) WantsJSON() bool

WantsJSON returns true if the request expects a JSON response based on Content-Type or Accept headers. Useful for dual HTML/JSON endpoints.

func (*ResponseContext) Writer

func (rc *ResponseContext) Writer() http.ResponseWriter

Writer returns the underlying http.ResponseWriter for advanced response handling when the ResponseContext helpers are not sufficient.

type ResponseObject

type ResponseObject struct {
	Description string                      `json:"description"`
	Headers     map[string]*HeaderObject    `json:"headers,omitempty"`
	Content     map[string]*MediaTypeObject `json:"content,omitempty"`
}

ResponseObject describes a single response in an Operation.

type ResponseOption

type ResponseOption struct {
	Description string
	Body        any
}

ResponseOption configures a single HTTP response in an Operation. Description is required; Body, if non-nil, is used to generate a schema.

type RouteOptions

type RouteOptions struct {
	Tags        []string
	Summary     string
	Description string
	OperationID string
	Deprecated  bool
	RequestBody any
	Responses   map[int]ResponseOption
	Parameters  []ParameterOption
}

RouteOptions holds OpenAPI metadata for a single route. Tags, Summary, Description, and OperationID map directly into the corresponding Operation fields. RequestBody, Responses, and Parameters drive schema generation for request bodies, responses, and parameters.

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router is a minimal HTTP router that supports dynamic routes with regex validation in path parameters and can mount subrouters. It provides middleware support, custom error handlers, and both traditional and enhanced handler functions.

func NewRouter

func NewRouter() *Router

NewRouter creates and returns a new Router instance with default configuration.

func (*Router) Delete

func (r *Router) Delete(pattern string, handler http.HandlerFunc, options ...*RouteOptions)

Delete registers a new route for HTTP DELETE requests using the standard handler signature.

func (*Router) DeleteFunc

func (r *Router) DeleteFunc(pattern string, handler HandlerFunc, options ...*RouteOptions)

DeleteFunc registers a new route for HTTP DELETE requests using the enhanced handler signature.

func (*Router) Get

func (r *Router) Get(pattern string, handler http.HandlerFunc, options ...*RouteOptions)

Get registers a new route for HTTP GET requests using the standard handler signature.

func (*Router) GetFunc

func (r *Router) GetFunc(pattern string, handler HandlerFunc, options ...*RouteOptions)

GetFunc registers a new route for HTTP GET requests using the enhanced handler signature.

func (*Router) Group

func (r *Router) Group(prefix string, mws ...Middleware) *Group

Group creates and returns a new Group with the given prefix. A group is a lightweight convenience wrapper that prefixes routes and can add its own middleware without creating a separate router instance.

func (*Router) Handle

func (r *Router) Handle(method, pattern string, handler http.HandlerFunc, opts ...*RouteOptions)

Handle registers a new route with the given HTTP method, URL pattern, and handler. If the router has a non-empty basePath, it is automatically prepended to the pattern. Optional RouteOptions can be provided for OpenAPI documentation.

func (*Router) HandleFunc

func (r *Router) HandleFunc(method, pattern string, handler HandlerFunc, opts ...*RouteOptions)

HandleFunc registers a new enhanced route that receives a ResponseContext instead of separate ResponseWriter and Request parameters. This enables cleaner error handling and response management with automatic data binding capabilities.

func (*Router) Patch

func (r *Router) Patch(pattern string, handler http.HandlerFunc, options ...*RouteOptions)

Patch registers a new route for HTTP PATCH requests using the standard handler signature.

func (*Router) PatchFunc

func (r *Router) PatchFunc(pattern string, handler HandlerFunc, options ...*RouteOptions)

PatchFunc registers a new route for HTTP PATCH requests using the enhanced handler signature.

func (*Router) Post

func (r *Router) Post(pattern string, handler http.HandlerFunc, options ...*RouteOptions)

Post registers a new route for HTTP POST requests using the standard handler signature.

func (*Router) PostFunc

func (r *Router) PostFunc(pattern string, handler HandlerFunc, options ...*RouteOptions)

PostFunc registers a new route for HTTP POST requests using the enhanced handler signature.

func (*Router) Put

func (r *Router) Put(pattern string, handler http.HandlerFunc, options ...*RouteOptions)

Put registers a new route for HTTP PUT requests using the standard handler signature.

func (*Router) PutFunc

func (r *Router) PutFunc(pattern string, handler HandlerFunc, options ...*RouteOptions)

PutFunc registers a new route for HTTP PUT requests using the enhanced handler signature.

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements the http.Handler interface. It first checks subrouters based on their base path, then its own routes. If a URL pattern matches but the HTTP method does not, a 405 Method Not Allowed is returned. If no routes match, a 404 Not Found is returned.

func (*Router) ServeOpenAPISpec

func (r *Router) ServeOpenAPISpec(path string, config OpenAPIConfig)

ServeOpenAPISpec makes your OpenAPI specification available at `path` (e.g. "/openapi.json")

func (*Router) ServeSwaggerUI

func (r *Router) ServeSwaggerUI(prefix string)

ServeSwaggerUI shows swaggerUI at `prefix` (e.g. "/docs")

func (*Router) SetMethodNotAllowedHandler

func (r *Router) SetMethodNotAllowedHandler(h http.Handler)

SetMethodNotAllowedHandler allows users to supply a custom http.Handler for requests that match a route pattern but use an unsupported HTTP method. If not set, a default 405 Method Not Allowed response is returned.

func (*Router) SetNotFoundHandler

func (r *Router) SetNotFoundHandler(h http.Handler)

SetNotFoundHandler allows users to supply a custom http.Handler for requests that do not match any route. If not set, the standard http.NotFound handler is used.

func (*Router) Static

func (r *Router) Static(urlPathPrefix string, subFS fs.FS)

Static mounts an fs.FS under the given URL prefix.

func (*Router) Subrouter

func (r *Router) Subrouter(prefix string) *Router

Subrouter creates a new Router mounted at the given prefix. The subrouter inherits the parent's context key, global middleware, and error handlers. Its routes will automatically receive the combined prefix.

func (*Router) URLParam

func (r *Router) URLParam(req *http.Request, key string) string

URLParam retrieves the URL parameter for the given key from the request context. It returns an empty string if the parameter is not present. This method should only be called within route handlers that were registered with this router.

func (*Router) Use

func (r *Router) Use(mws ...Middleware)

Use registers one or more middleware functions that will be applied globally to every matched route handler. Middleware is applied in the order it is registered.

type SchemaObject

type SchemaObject struct {
	Ref                  string                   `json:"$ref,omitempty"`
	Type                 string                   `json:"type,omitempty"`
	Format               string                   `json:"format,omitempty"`
	Properties           map[string]*SchemaObject `json:"properties,omitempty"`
	Items                *SchemaObject            `json:"items,omitempty"`
	Description          string                   `json:"description,omitempty"`
	Example              any                      `json:"example,omitempty"`
	Required             []string                 `json:"required,omitempty"`
	Nullable             bool                     `json:"nullable,omitempty"`
	Enum                 any                      `json:"enum,omitempty"`
	AdditionalProperties *SchemaObject            `json:"additionalProperties,omitempty"`
}

SchemaObject represents an OpenAPI Schema or a reference to one.

type SecurityHeadersConfig

type SecurityHeadersConfig struct {
	// ContentTypeOptions sets the X-Content-Type-Options header.
	// Defaults to "nosniff". Set to "" to disable.
	ContentTypeOptions string
	// FrameOptions sets the X-Frame-Options header.
	// Defaults to "DENY". Other common values: "SAMEORIGIN". Set to "" to disable.
	FrameOptions string
	// ReferrerPolicy sets the Referrer-Policy header.
	// Defaults to "strict-origin-when-cross-origin". Set to "" to disable.
	ReferrerPolicy string
	// HSTSMaxAgeSeconds sets the max-age for Strict-Transport-Security (HSTS).
	// If > 0, HSTS header is set for HTTPS requests. Defaults to 0 (disabled).
	HSTSMaxAgeSeconds int
	// HSTSIncludeSubdomains adds `includeSubDomains` to HSTS header. Defaults to true if HSTSMaxAgeSeconds > 0.
	HSTSIncludeSubdomains *bool // Use pointer for explicit false vs unset
	// HSTSPreload adds `preload` to HSTS header. Use with caution. Defaults to false.
	HSTSPreload bool
	// ContentSecurityPolicy sets the Content-Security-Policy header.
	// Defaults to "". This policy is complex and highly site-specific.
	ContentSecurityPolicy string
	// PermissionsPolicy sets the Permissions-Policy header (formerly Feature-Policy).
	// Defaults to "". Example: "geolocation=(), microphone=()"
	PermissionsPolicy string
}

SecurityHeadersConfig holds configuration for SecurityHeadersMiddleware.

type StringFlag

type StringFlag struct {
	// Name is the primary identifier for the flag (e.g., "output"). Used as --name. (Required)
	Name string
	// Aliases provide alternative names (e.g., "o"). Single letters are used as -o.
	Aliases []string
	// Usage provides a brief description of the flag's purpose for help text. (Required)
	Usage string
	// Default sets the default value if the flag is not provided.
	Default string
	// Required indicates if the user must provide this flag.
	Required bool
}

StringFlag defines a flag that accepts a string value.

func (*StringFlag) Apply

func (f *StringFlag) Apply(set *flag.FlagSet, cli *CLI) error

Apply registers the string flag with the flag.FlagSet.

func (*StringFlag) GetAliases

func (f *StringFlag) GetAliases() []string

GetAliases returns the aliases for the flag.

func (*StringFlag) GetName

func (f *StringFlag) GetName() string

GetName returns the primary name of the flag.

func (*StringFlag) IsRequired

func (f *StringFlag) IsRequired() bool

IsRequired returns true if the flag must be provided.

func (*StringFlag) String

func (f *StringFlag) String() string

String returns the help text representation of the flag.

func (*StringFlag) Validate

func (f *StringFlag) Validate(set *flag.FlagSet) error

Validate checks if the required flag was provided and is not empty.

type StringSliceFlag

type StringSliceFlag struct {
	// Name is the primary identifier for the flag (e.g., "tag"). Used as --name. (Required)
	Name string
	// Aliases provide alternative names (e.g., "t"). Single letters are used as -t.
	Aliases []string
	// Usage provides a brief description of the flag's purpose for help text. (Required)
	Usage string
	// Default sets the default value if the flag is not provided.
	Default []string
	// Required indicates if the user must provide this flag at least once.
	Required bool
}

StringSliceFlag defines a flag that accepts multiple string values. The flag can be repeated on the command line (e.g., --tag foo --tag bar).

func (*StringSliceFlag) Apply

func (f *StringSliceFlag) Apply(set *flag.FlagSet, cli *CLI) error

Apply registers the string slice flag with the flag.FlagSet using a custom Value.

func (*StringSliceFlag) GetAliases

func (f *StringSliceFlag) GetAliases() []string

GetAliases returns the aliases for the flag.

func (*StringSliceFlag) GetName

func (f *StringSliceFlag) GetName() string

GetName returns the primary name of the flag.

func (*StringSliceFlag) IsRequired

func (f *StringSliceFlag) IsRequired() bool

IsRequired returns true if the flag must be provided.

func (*StringSliceFlag) String

func (f *StringSliceFlag) String() string

String returns the help text representation of the flag.

func (*StringSliceFlag) Validate

func (f *StringSliceFlag) Validate(set *flag.FlagSet) error

Validate checks if the required flag was provided and resulted in a non-empty slice.

type TimeoutConfig

type TimeoutConfig struct {
	// Duration is the maximum time allowed for the handler to process the request.
	Duration time.Duration
	// TimeoutMessage is the message sent in the response body on timeout.
	// Defaults to "Service timed out".
	TimeoutMessage string
	// TimeoutHandler allows custom logic to run on timeout. If nil, the default
	// http.TimeoutHandler behavior (503 Service Unavailable with message) is used.
	TimeoutHandler http.Handler
}

TimeoutConfig holds configuration for TimeoutMiddleware.

type TrailingSlashRedirectConfig

type TrailingSlashRedirectConfig struct {
	// AddSlash enforces trailing slashes (redirects /path to /path/). Defaults to false (removes slash).
	AddSlash bool
	// RedirectCode is the HTTP status code used for redirection.
	// Defaults to http.StatusMovedPermanently (301). Use 308 for POST/PUT etc.
	RedirectCode int
}

TrailingSlashRedirectConfig holds configuration for TrailingSlashRedirectMiddleware.

type ValidationErrors

type ValidationErrors []error

ValidationErrors collects one or more validation violations and implements error.

func (ValidationErrors) Error

func (ve ValidationErrors) Error() string

Error joins all contained error messages into a single string.

Jump to

Keyboard shortcuts

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