Reference

Table of Contents

Variables

ErrMissingContentType

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

ErrMissingContentType indicates the Content-Type header was absent.


ErrUnsupportedContentType

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

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


Functions

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.


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.


GetBasicAuthUserWithKey

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

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


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.


GetCSRFTokenWithKey

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

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


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.


GetRealIPWithKey

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

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


GetRequestID

func GetRequestID(ctx context.Context) string

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


GetRequestIDWithKey

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

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


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.


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.


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.


NewBufferingResponseWriterInterceptor

func NewBufferingResponseWriterInterceptor(w http.ResponseWriter) *bufferingResponseWriterInterceptor

NewBufferingResponseWriterInterceptor creates a new buffering interceptor.


NewResponseWriterInterceptor

func NewResponseWriterInterceptor(w http.ResponseWriter) *responseWriterInterceptor

NewResponseWriterInterceptor creates a new interceptor.


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

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.


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.


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.


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


Methods

Apply

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

Apply registers the bool flag with the flag.FlagSet.


GetAliases

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

GetAliases returns the aliases for the flag.


GetName

func (f *BoolFlag) GetName() string

GetName returns the primary name of the flag.


IsRequired

func (f *BoolFlag) IsRequired() bool

IsRequired always returns false for boolean flags.


String

func (f *BoolFlag) String() string

String returns the help text representation of the flag.


Validate

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

Validate always returns nil for boolean flags.


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.


Associated Functions

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.


Methods

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


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


ShowHelp

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

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


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.


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.


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.


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.


Methods

ShowHelp

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

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


Components

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

Components holds reusable schema definitions for the OpenAPI spec.


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.


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.


Methods

Args

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

Args returns the non-flag arguments remaining after parsing for the current 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.


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.


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.


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.


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.


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


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.


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 ) and container elements (like

). Elements can be chained using fluent API methods for convenient construction.


Associated Functions

A

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

A creates an anchor element.


Abbr

func Abbr(content ...HTMLElement) *Element

Abbr creates an abbreviation element.


Address

func Address(content ...HTMLElement) *Element

Address creates an

semantic element.


Article

func Article(content ...HTMLElement) *Element

Article creates an

semantic element.


Aside

func Aside(content ...HTMLElement) *Element

Aside creates an