azugo

package module
v0.40.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 49 Imported by: 51

README

azugo

Opinionated GoLang web framework for microservices based on FastHTTP.

Features
Special Environment variables used by the Azugo framework
Core
  • ENVIRONMENT - App environment setting (allowed values are development, test, staging and production).
  • LOG_TYPE - Log type (defaults to console, allowed values are console, file, otel (provided by azugo.io/opentelemetry) or other registered log drivers).
  • LOG_LEVEL - Minimal log level (defaults to info, allowed values are debug, info, warn, error, dpanic, panic, fatal).
  • LOG_FORMAT - Log output format (defaults to console in development environment and ecsjson in staging and production).
  • LOG_OUTPUT - Log output location (defaults to stderr, allowed values are stderr, stdout, file path or file:// URL and other values supported by registered log drivers).
  • LOG_STACKTRACE - Enable stack traces for error level and above regardless of environment (defaults to false).
  • LOG_TYPE_SECONDARY - Secondary log type (see LOG_TYPE).
  • LOG_LEVEL_SECONDARY - Secondary log level (defaults to info, see LOG_LEVEL).
  • LOG_FORMAT_SECONDARY - Secondary log format (see LOG_FORMAT).
  • LOG_OUTPUT_SECONDARY - Secondary log output location (see LOG_OUTPUT).
Server
  • SERVER_URLS - Server URL or multiple URLs separated by semicolons to listen on.
  • SERVER_HTTPS_CERTIFICATE_PEM_FILE - Path to PEM file for HTTPS certificate.
  • SERVER_READ_TIMEOUT - Maximum duration for reading the full request including body (defaults to 30s).
  • SERVER_WRITE_TIMEOUT - Maximum duration for writing the response (defaults to 10s).
  • SERVER_IDLE_TIMEOUT - Maximum duration to wait for the next request on a keep-alive connection (defaults to 75s).
  • SERVER_MAX_REQUEST_BODY_SIZE - Maximum request body size in bytes (defaults to 4194304 (4MB)).
  • SERVER_SHUTDOWN_TIMEOUT - Maximum duration to wait for active connections to finish on graceful shutdown (defaults to 30s).
  • BASE_PATH - Base path for the app if deployed in a subdirectory.
  • ACCESS_LOG_ENABLED - Enable access logs (defaults to true).
Reverse Proxy
  • REVERSE_PROXY_TRUSTED_IPS - Semicolon-separated list of trusted proxy IP addresses or CIDR ranges (defaults to 127.0.0.1).
  • REVERSE_PROXY_TRUSTED_HEADERS - Semicolon-separated list of trusted proxy headers (defaults to X-Real-IP;X-Forwarded-For).
  • REVERSE_PROXY_LIMIT - Maximum number of trusted proxies in chain (defaults to 1).
CORS
  • CORS_ORIGINS - Semicolon-separated list of allowed CORS origins.
Metrics
  • METRICS_ENABLED - Enable Prometheus metrics endpoint (defaults to true).
  • METRICS_PATH - Metrics endpoint path (defaults to /metrics).
  • METRICS_TRUSTED_IPS - Semicolon-separated list of trusted IP addresses or CIDR ranges allowed to access the metrics endpoint (defaults to 127.0.0.1).
Health Check
  • HEALTHZ_ENABLED - Enable health check endpoint (defaults to true).
  • HEALTHZ_TRUSTED_IPS - Semicolon-separated list of trusted IP addresses or CIDR ranges allowed to access the health check endpoint (defaults to all loopback and private network ranges: 127.0.0.0/8, ::1/128, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7).
Pagination
  • PAGING_DEFAULT_PAGE_SIZE - Default page size for paginated responses (defaults to 20).
  • PAGING_MAX_PAGE_SIZE - Maximum allowed page size for paginated responses (defaults to 100).
Flash
  • FLASH_COOKIE_NAME - Name of the cookie carrying the flash record ID between requests (defaults to flash).
  • FLASH_TTL - Duration an unread flash record waits.
Cache

Redis-backed cache types require Redis 6.2 or later, or any Valkey version.

  • CACHE_TYPE - Cache type to use (defaults to memory, allowed values are memory, redis, redis-cluster, redis-sentinel).
  • CACHE_TTL - Duration to keep items in cache (defaults to 0 meaning never expire).
  • CACHE_KEY_PREFIX - Prefix all cache keys with specified value.
  • CACHE_CONNECTION - Connection string for non-memory cache backends.
  • CACHE_PASSWORD - Password for cache connection.
  • CACHE_PASSWORD_FILE - File to read value for CACHE_PASSWORD from.
  • CACHE_CLIENT_CACHE - Enable server-assisted client-side caching support on Redis connections (defaults to true).
  • CACHE_CLIENT_CACHE_TTL - Default duration to keep values in the in-process client-side cache (defaults to 0 meaning disabled).
  • CACHE_CLIENT_CACHE_SIZE - Client-side cache memory bound in bytes per Redis connection (defaults to 16777216, i.e. 16 MiB).
Special thanks to

Documentation

Overview

Package azugo is a fast and simple web framework for building APIs.

Index

Constants

View Source
const (
	InstrumentationRequest = "http-request"
	InstrumentationPanic   = "http-panic"
)

Instrumentation operation names.

View Source
const DefaultMetricPath string = "/metrics"

DefaultMetricPath is the default path for the Prometheus metrics endpoint.

View Source
const MethodWild http.Method = "*"

MethodWild wild HTTP method.

Variables

This section is empty.

Functions

func InstrRequest added in v0.16.0

func InstrRequest(op string, args ...any) (string, bool)

InstrRequest returns path if the request is router handler request.

func NewErrorResponse

func NewErrorResponse(err error) *http.ErrorResponse

NewErrorResponse creates an error response from the given error.

Types

type App

type App struct {
	*core.App

	// Metrics options
	MetricsOptions MetricsOptions

	// Healthz options
	HealthzOptions TrustedSource

	// Server options
	ServerOptions ServerOptions
	// contains filtered or unexported fields
}

App is the main application instance.

func New

func New(opts ...*core.App) *App

New creates a new Azugo application.

func (*App) AddHTTPClientOption added in v0.16.0

func (a *App) AddHTTPClientOption(opt http.Option)

AddHTTPClientOption adds a additional option to HTTP client.

func (*App) Any

func (a *App) Any(path string, handler RequestHandler)

Any is a shortcut for all HTTP methods handler

WARNING: Use only for routes where the request method is not important.

func (*App) ApplyConfig added in v0.5.0

func (a *App) ApplyConfig()

ApplyConfig applies the loaded configuration to the application.

func (*App) Config

func (a *App) Config() *config.Configuration

Config returns application configuration.

Panics if configuration is not loaded.

func (*App) Connect

func (a *App) Connect(path string, handler RequestHandler)

Connect is a shortcut for HTTP CONNECT method handler.

func (*App) Delete

func (a *App) Delete(path string, handler RequestHandler)

Delete is a shortcut for HTTP DELETE method handler.

func (*App) Get

func (a *App) Get(path string, handler RequestHandler)

Get is a shortcut for HTTP GET method handler.

func (*App) Group

func (a *App) Group(path string) Router

Group returns a new group. Path auto-correction, including trailing slashes, is enabled by default.

func (*App) HTTPClient added in v0.16.0

func (a *App) HTTPClient() http.Client

HTTPClient returns HTTP client instance.

func (*App) Handle

func (a *App) Handle(method http.Method, path string, handler RequestHandler)

Handle registers a new request handler with the given path and method.

For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*App) Handler

func (a *App) Handler(ctx *fasthttp.RequestCtx)

Handler makes the router implement the fasthttp.Handler interface.

func (*App) Head

func (a *App) Head(path string, handler RequestHandler)

Head is a shortcut for HTTP HEAD method handler.

func (*App) Mutable

func (a *App) Mutable(v bool)

Mutable allows updating the route handler

Disabled by default. WARNING: Use with care. It could generate unexpected behaviors.

func (*App) Options

func (a *App) Options(path string, handler RequestHandler)

Options is a shortcut for HTTP OPTIONS method handler.

func (*App) Patch

func (a *App) Patch(path string, handler RequestHandler)

Patch is a shortcut for HTTP PATCH method handler.

func (*App) Post

func (a *App) Post(path string, handler RequestHandler)

Post is a shortcut for HTTP POST method handler.

func (*App) Proxy

func (a *App) Proxy(path string, options ...ProxyOption)

Proxy is helper to proxy requests to another host.

func (*App) Put

func (a *App) Put(path string, handler RequestHandler)

Put is a shortcut for HTTP PUT method handler.

func (*App) Query added in v0.35.0

func (a *App) Query(path string, handler RequestHandler)

Query is a shortcut for HTTP QUERY method handler.

func (*App) RouterOptions

func (a *App) RouterOptions() *RouterOptions

RouterOptions for default router.

func (*App) Routes

func (a *App) Routes() map[http.Method][]string

Routes returns all registered routes grouped by method.

func (*App) SetConfig

func (a *App) SetConfig(_ *cobra.Command, conf *config.Configuration)

SetConfig binds application configuration to the application.

func (*App) SetExtendedContext deprecated added in v0.25.0

func (a *App) SetExtendedContext(ext ExtendedContext)

SetExtendedContext sets the context extension.

Deprecated: use Context.SetContext from a handler or middleware to install the effective request context instead. See ExtendedContext for details.

func (*App) SetRouterSwitch added in v0.5.0

func (a *App) SetRouterSwitch(r RouteSwitcher)

SetRouterSwitch sets router switcher that selects router based on request context.

func (*App) Start

func (a *App) Start() error

Start web application.

func (*App) StaticEmbedded added in v0.16.0

func (a *App) StaticEmbedded(path string, f *embed.FS, opts ...StaticOption) error

StaticEmbedded serves files from an embedded filesystem at the given path.

func (*App) Stop added in v0.35.1

func (a *App) Stop()

Stop web application and its services waiting for active connections to finish.

func (*App) Trace

func (a *App) Trace(path string, handler RequestHandler)

Trace is a shortcut for HTTP TRACE method handler.

func (*App) Use

func (a *App) Use(middlewares ...RequestHandlerFunc)

Use appends a middleware to the router. Middlewares will be executed in the order they were added. It will be executed only for the routes that have been added after the middleware was registered.

func (*App) UsePriority added in v0.33.1

func (a *App) UsePriority(middlewares ...RequestHandlerFunc)

UsePriority appends a middleware to the priority chain, which runs before (outer to) all middlewares registered with Use.

type BadRequestError added in v0.13.0

type BadRequestError struct {
	Description string
	Err         error
}

BadRequestError is an error that occurs when request is malformed.

func (BadRequestError) Error added in v0.13.0

func (e BadRequestError) Error() string

func (BadRequestError) SafeError added in v0.19.1

func (e BadRequestError) SafeError() string

SafeError returns a safe error message for BadRequestError.

func (BadRequestError) StatusCode added in v0.13.0

func (BadRequestError) StatusCode() int

StatusCode returns the HTTP status code for BadRequestError.

type BodyCtx

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

BodyCtx represents the request body.

func (*BodyCtx) Bytes

func (b *BodyCtx) Bytes() []byte

Bytes returns the request body as raw bytes.

func (*BodyCtx) JSON

func (b *BodyCtx) JSON(v any) error

JSON unmarshals the request body into provided structure. Optionally calls Validate method of the structure if it implements validation.Validator interface.

func (*BodyCtx) WriteTo

func (b *BodyCtx) WriteTo(w io.Writer) (int64, error)

WriteTo copies the request raw body to the provided writer.

Warning: Always returns 0 as not possible to determine the number of bytes written.

func (*BodyCtx) XML

func (b *BodyCtx) XML(v any) error

XML unmarshals the request body into provided structure.

type CORSOptions

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

CORSOptions is options for CORS middleware.

func (*CORSOptions) AllowCredentials added in v0.14.0

func (c *CORSOptions) AllowCredentials() bool

AllowCredentials returns flag if CORS credentials are alloweds.

func (*CORSOptions) Headers

func (c *CORSOptions) Headers() string

Headers returns allowed CORS headers.

func (*CORSOptions) Methods

func (c *CORSOptions) Methods() string

Methods returns allowed CORS methods.

func (*CORSOptions) SetHeaders

func (c *CORSOptions) SetHeaders(headers ...string) *CORSOptions

SetHeaders sets allowed CORS methods.

func (*CORSOptions) SetMethods

func (c *CORSOptions) SetMethods(methods ...string) *CORSOptions

SetMethods sets allowed CORS methods.

func (*CORSOptions) SetOrigins

func (c *CORSOptions) SetOrigins(origins ...string) *CORSOptions

SetOrigins sets allowed CORS origins. Set to `*` to allow all origins.

func (*CORSOptions) ValidOrigin

func (c *CORSOptions) ValidOrigin(origin string) bool

ValidOrigin returns true if the CORS origin is allowed.

type Context

type Context struct {

	// Header access methods
	Header HeaderCtx
	// Cookie access methods
	Cookie CookieCtx
	// Flash carries one-shot state to the next request after redirect.
	Flash FlashCtx
	// Query access methods
	Query QueryCtx
	// Body access methods
	Body BodyCtx
	// Form access methods
	Form FormCtx
	// Route parameters access methods
	Params ParamsCtx
	// contains filtered or unexported fields
}

Context holds the state and helpers for a single HTTP request.

func RequestContext added in v0.17.0

func RequestContext(ctx context.Context) *Context

RequestContext returns the request context carried by ctx, or nil if there is none.

func (*Context) Accepts

func (c *Context) Accepts(contentType string) bool

Accepts checks if provided content type is acceptable for client.

func (*Context) AcceptsExplicit

func (c *Context) AcceptsExplicit(contentType string) bool

AcceptsExplicit checks if provided content type is explicitly acceptable for client.

func (*Context) AddLogFields added in v0.8.0

func (c *Context) AddLogFields(fields ...zap.Field) error

AddLogFields add fields to context logger.

func (*Context) AfterFunc added in v0.37.2

func (c *Context) AfterFunc(f func()) func() bool

AfterFunc registers f to run once the Context is canceled and returns a stop function reporting whether it removed the registration.

func (*Context) App

func (c *Context) App() *App

App returns the application.

func (*Context) BasePath

func (c *Context) BasePath() string

BasePath returns the base path.

func (*Context) BaseURL

func (c *Context) BaseURL() string

BaseURL returns the base URL for the request.

func (*Context) ContentLength added in v0.35.0

func (c *Context) ContentLength() int

ContentLength returns the request Content-Length header value.

It may be negative if the request body size is unknown.

func (*Context) ContentType

func (c *Context) ContentType(contentType string, charset ...string)

ContentType sets the Content-Type header for the response with optionally setting charset if provided. This method is chainable.

func (*Context) Context

func (c *Context) Context() *fasthttp.RequestCtx

Context returns *fasthttp.RequestCtx that carries a deadline a cancellation signal, and other values across API boundaries.

func (*Context) Deadline

func (c *Context) Deadline() (time.Time, bool)

Deadline returns the time when work done on behalf of this context should be canceled. Deadline returns ok==false when no deadline is set. Successive calls to Deadline return the same results.

func (*Context) Done

func (c *Context) Done() <-chan struct{}

Done returns a channel that is closed when the request completes, the server is shutting down or a cancellable context installed via SetContext is canceled. The channel is created lazily and is safe to hand to code that outlives the handler.

func (*Context) Env

func (c *Context) Env() core.Environment

Env returns the application environment.

func (*Context) Err

func (c *Context) Err() error

Err returns nil while the request is being served and a non-nil error after the Context has been canceled.

func (*Context) Error

func (c *Context) Error(err error)

Error return the error response. Calls either custom ErrorHandler or default if not specified.

func (*Context) HTTPClient added in v0.16.0

func (c *Context) HTTPClient() http.Client

HTTPClient returns the HTTP client with the current context.

func (*Context) Host

func (c *Context) Host() string

Host returns requested host.

If the request comes from trusted proxy it will use X-Forwarded-Host header.

func (*Context) ID added in v0.8.0

func (c *Context) ID() string

ID returns the unique request identifier.

func (*Context) IP

func (c *Context) IP() net.IP

IP returns the client's network IP address.

func (*Context) IsSkipRequestLog added in v0.33.1

func (c *Context) IsSkipRequestLog() bool

IsSkipRequestLog reports whether request logging and tracing are disabled for the current request.

func (*Context) IsTLS

func (c *Context) IsTLS() bool

IsTLS returns true if the underlying connection is TLS.

If the request comes from trusted proxy it will use X-Forwarded-Proto header.

func (*Context) IsTrustedProxy

func (c *Context) IsTrustedProxy() bool

IsTrustedProxy checks whether the proxy that request is coming from can be trusted.

func (*Context) JSON

func (c *Context) JSON(obj any)

JSON serializes the given struct as JSON and sets it as the response body.

func (*Context) Log

func (c *Context) Log() *zap.Logger

Log returns the request logger, building it lazily on first use.

func (*Context) LogFields added in v0.35.1

func (c *Context) LogFields() []zap.Field

LogFields returns the fields added to the context logger.

func (*Context) MaxPageSize added in v0.19.0

func (c *Context) MaxPageSize() int

MaxPageSize returns the maximum page size.

func (*Context) Method

func (c *Context) Method() http.Method

Method returns the request method.

func (*Context) NotFound

func (c *Context) NotFound()

NotFound returns an not found response. Calls either custom NotFound or default if not specified.

func (*Context) Paging

func (c *Context) Paging() *paginator.Paginator

Paging returns a Paginator with page size from query parameters.

func (*Context) Path

func (c *Context) Path() string

Path returns the path part of the request URL.

func (*Context) Protocol added in v0.35.0

func (c *Context) Protocol() string

Protocol returns the HTTP protocol version of the request.

func (*Context) Raw

func (c *Context) Raw(data []byte)

Raw sets response body, but without copying it.

WARNING: From this point onward the body argument must not be changed.

func (*Context) Redirect

func (c *Context) Redirect(target string)

Redirect the request to target: either a bare path, prefixed with BasePath() or an absolute URL matching the current app base URL. Unless a redirect status was already set, GET and HEAD requests answer 302 (Found) and every other method 303 (See Other), so a form POST is always followed by a GET.

func (*Context) RedirectUnsafe added in v0.36.0

func (c *Context) RedirectUnsafe(url string)

RedirectUnsafe redirects the request to a given URL, choosing the status like Redirect.

func (*Context) Referer added in v0.35.0

func (c *Context) Referer() string

Referer returns the client's Referer, if sent in the request.

func (*Context) ReplaceLogger added in v0.8.0

func (c *Context) ReplaceLogger(logger *zap.Logger) error

ReplaceLogger replaces current context logger with custom.

func (*Context) Request

func (c *Context) Request() *fasthttp.Request

Request return the *fasthttp.Request object This allows you to use all fasthttp request methods https://godoc.org/github.com/valyala/fasthttp#Request

func (*Context) Response

func (c *Context) Response() *fasthttp.Response

Response return the *fasthttp.Response object This allows you to use all fasthttp response methods https://godoc.org/github.com/valyala/fasthttp#Response

func (*Context) RouterOptions added in v0.5.0

func (c *Context) RouterOptions() *RouterOptions

RouterOptions returns the router options.

func (*Context) RouterPath

func (c *Context) RouterPath() string

RouterPath returns the registered router path.

func (*Context) SetContext added in v0.33.0

func (c *Context) SetContext(ctx context.Context)

SetContext installs the effective request context.

ctx MUST be derived from c.Context() (the underlying request context), for example using context.WithValue(c.Context(), key, value).

Passing a nil ctx resets the effective context back to the base request context.

func (*Context) SetMaxPageSize added in v0.19.0

func (c *Context) SetMaxPageSize(maxPageSize int)

SetMaxPageSize sets the maximum page size for current context. Set to 0 to use the default value from the configuration.

func (*Context) SetPaging

func (c *Context) SetPaging(values map[string]string, paginator *paginator.Paginator)

SetPaging sets pagination headers and metadata on the response.

func (*Context) SetUser

func (c *Context) SetUser(u User)

SetUser sets authorized user.

func (*Context) SetUserValue

func (c *Context) SetUserValue(name string, value any)

SetUserValue stores the given value (arbitrary object) under the given key in context.

The value stored in contex may be obtained by UserValue.

This functionality may be useful for passing arbitrary values between functions involved in request processing.

All the values are removed from context after returning from the top RequestHandler. Additionally, Close method is called on each value implementing io.Closer before removing the value from context.

func (*Context) SkipMetrics added in v0.31.0

func (c *Context) SkipMetrics()

SkipMetrics sets to skip metrics recording for current request.

func (*Context) SkipRequestLog added in v0.8.0

func (c *Context) SkipRequestLog()

SkipRequestLog sets to skip request log entry and tracing for current request.

func (*Context) StatusCode

func (c *Context) StatusCode(status int)

StatusCode sets the HTTP status code for the response. This method is chainable.

func (*Context) Stream added in v0.16.0

func (c *Context) Stream(r io.Reader)

Stream sets the response body to the given stream.

Close() is called after finishing reading all body data if it implements io.Closer.

func (*Context) Text

func (c *Context) Text(text string)

Text sets the response body to the given text.

func (*Context) Time added in v0.35.0

func (c *Context) Time() time.Time

Time when the request was received by the server.

func (*Context) User

func (c *Context) User() User

User returns authorized user or.

func (*Context) UserAgent

func (c *Context) UserAgent() string

UserAgent returns the client's User-Agent, if sent in the request.

func (*Context) UserValue

func (c *Context) UserValue(name string) any

UserValue returns the value stored via SetUserValue under the given key.

func (*Context) Validate

func (c *Context) Validate() *validation.Validate

Validate returns validation service instance.

func (*Context) Value

func (c *Context) Value(key any) any

Value returns the value associated with this context for key, or nil if no value is associated with key. Successive calls to Value with the same key returns the same result.

Use context values only for request-scoped data that transits processes and API boundaries, not for passing optional parameters to functions.

A key identifies a specific value in a Context. Functions that wish to store values in Context typically allocate a key in a global variable then use that key as the argument to context.WithValue and Context.Value. A key can be any type that supports equality; packages should define keys as an unexported type to avoid collisions.

Packages that define a Context key should provide type-safe accessors for the values stored using that key:

// Package user defines a User type that's stored in Contexts.
package user

import "context"

// User is the type of value stored in the Contexts.
type User struct {...}

// key is an unexported type for keys defined in this package.
// This prevents collisions with keys defined in other packages.
type key int

// userKey is the key for user.User values in Contexts. It is
// unexported; clients use user.NewContext and user.FromContext
// instead of using this key directly.
var userKey key

// NewContext returns a new Context that carries value u.
func NewContext(ctx context.Context, u *User) context.Context {
	return context.WithValue(ctx, userKey, u)
}

// FromContext returns the User value stored in ctx, if any.
func FromContext(ctx context.Context) (*User, bool) {
	u, ok := ctx.Value(userKey).(*User)
	return u, ok
}

type Contexter added in v0.17.0

type Contexter interface {
	// RequestContext returns request context.
	RequestContext() context.Context
}

Contexter is an interface that checks if type has a request context.

type CookieCtx added in v0.33.0

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

CookieCtx provides cookie read and write helpers on an HTTP context.

func (*CookieCtx) All added in v0.33.0

func (c *CookieCtx) All() iter.Seq2[string, string]

All returns an iterator over all request cookies as bare name and value pairs, resolving prefixed variants the same way Get does: weaker variants of a cookie are skipped.

func (*CookieCtx) Clear added in v0.33.0

func (c *CookieCtx) Clear(name string, opts ...CookieOption)

Clear the named cookie on the client. Pass the same options that were used when setting the cookie. With CookieDefaultSecurity every prefixed variant the request carries is cleared, so a cookie set under a different scheme (e.g. __Host- over TLS) is removed as well.

func (*CookieCtx) Get added in v0.33.0

func (c *CookieCtx) Get(name string) string

Get the value of the request cookie. A cookie written with CookieDefaultSecurity is found under its bare name: a __Host- variant wins over __Secure-, which wins over the bare name.

Returns empty value if no cookie is present.

func (*CookieCtx) Keys added in v0.33.0

func (c *CookieCtx) Keys() iter.Seq[string]

Keys returns an iterator over all request cookie names, with the __Host- and __Secure- prefixes stripped and the variants of one cookie collapsed into a single name.

func (*CookieCtx) Set added in v0.33.0

func (c *CookieCtx) Set(name, value string, opts ...CookieOption)

Set a response cookie with the given name and value.

type CookieDomain added in v0.33.0

type CookieDomain string

CookieDomain sets the Domain attribute of a response cookie.

type CookieExpires added in v0.33.0

type CookieExpires time.Time

CookieExpires sets the Expires attribute of a response cookie.

type CookieHTTPOnly added in v0.33.0

type CookieHTTPOnly bool

CookieHTTPOnly sets or clears the HttpOnly flag on a response cookie.

type CookieMaxAge added in v0.33.0

type CookieMaxAge time.Duration

CookieMaxAge sets the Max-Age attribute of a response cookie.

type CookieOption added in v0.33.0

type CookieOption interface {
	// contains filtered or unexported methods
}

CookieOption is an option for setting a response cookie.

func CookieDefaultSecurity added in v0.33.0

func CookieDefaultSecurity() CookieOption

CookieDefaultSecurity applies secure-by-default attributes to a response cookie and automatically selects the strongest cookie-name prefix the request allows:

  • __Host- when the cookie is Secure and scoped to the root path: forces Secure, Path="/" and no Domain.
  • __Secure- when the cookie is Secure but scoped below the root, either by a non-root base path or an explicit CookiePath: forces Secure and keeps that Path.
  • no prefix when the cookie is not Secure (development over plain HTTP).

It also sets HttpOnly, an empty Domain (host-only) and SameSite=Lax.

SameSite and Path may be overridden by passing an explicit option. Secure, Domain and HttpOnly are enforced after all other options and cannot be downgraded.

type CookiePath added in v0.33.0

type CookiePath string

CookiePath sets the Path attribute of a response cookie.

type CookieSameSite added in v0.33.0

type CookieSameSite fasthttp.CookieSameSite

CookieSameSite controls the SameSite attribute of a cookie.

const (
	// CookieSameSiteDisabled omits the SameSite attribute.
	CookieSameSiteDisabled CookieSameSite = CookieSameSite(fasthttp.CookieSameSiteDisabled)
	// CookieSameSiteDefault sets SameSite without a mode qualifier.
	CookieSameSiteDefault CookieSameSite = CookieSameSite(fasthttp.CookieSameSiteDefaultMode)
	// CookieSameSiteLax sets SameSite=Lax.
	CookieSameSiteLax CookieSameSite = CookieSameSite(fasthttp.CookieSameSiteLaxMode)
	// CookieSameSiteStrict sets SameSite=Strict.
	CookieSameSiteStrict CookieSameSite = CookieSameSite(fasthttp.CookieSameSiteStrictMode)
	// CookieSameSiteNone sets SameSite=None (requires Secure=true).
	CookieSameSiteNone CookieSameSite = CookieSameSite(fasthttp.CookieSameSiteNoneMode)
)

type CookieSecure added in v0.33.0

type CookieSecure bool

CookieSecure sets or clears the Secure flag on a response cookie.

type ErrorHeaders added in v0.33.0

type ErrorHeaders interface {
	ErrorHeaders() iter.Seq2[string, string]
}

ErrorHeaders is an interface that an error can implement to return additional HTTP response headers to set when the error is handled.

type ErrorMarshaler added in v0.33.0

type ErrorMarshaler interface {
	MarshalError(contentType string) (body []byte, ct string, ok bool)
}

ErrorMarshaler is an interface that an error can implement to provide a custom response body. Return false to fallback to default formatting.

type ExtendedContext deprecated added in v0.25.0

type ExtendedContext interface {
	// Context returns extended context.
	Context(ctx context.Context) context.Context
}

ExtendedContext is an interface that can be implemented to extend the context.

Deprecated: use Context.SetContext to install the effective request context instead.

type FlashCtx added in v0.39.0

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

FlashCtx carries one-shot state from this request to the next one.

func (*FlashCtx) Error added in v0.39.0

func (f *FlashCtx) Error(text string)

Error message for the next request.

func (*FlashCtx) Errors added in v0.39.0

func (f *FlashCtx) Errors() []string

Errors returns the error messages for this request.

func (*FlashCtx) FieldError added in v0.39.0

func (f *FlashCtx) FieldError(field, text string)

FieldError attaches a validation message to a form field for the next request.

func (*FlashCtx) FieldErrorFor added in v0.39.0

func (f *FlashCtx) FieldErrorFor(field string) string

FieldErrorFor returns the error for field.

func (*FlashCtx) FieldErrors added in v0.39.0

func (f *FlashCtx) FieldErrors() map[string]string

FieldErrors returns every field error for this request.

func (*FlashCtx) Get added in v0.39.0

func (f *FlashCtx) Get(key string, v any) (bool, error)

Get decodes the value left under key into v if it was present.

func (*FlashCtx) Has added in v0.39.0

func (f *FlashCtx) Has() bool

Has reports whether there is anything to read.

func (*FlashCtx) Info added in v0.39.0

func (f *FlashCtx) Info(text string)

Info message for the next request.

func (*FlashCtx) Infos added in v0.39.0

func (f *FlashCtx) Infos() []string

Infos returns the informational messages for this request.

func (*FlashCtx) Keep added in v0.39.0

func (f *FlashCtx) Keep()

Keep re-flashes what the previous request for one more request.

func (*FlashCtx) Now added in v0.39.0

func (f *FlashCtx) Now()

Now makes the values queued in this request readable in this request too.

func (*FlashCtx) Set added in v0.39.0

func (f *FlashCtx) Set(key string, value any) error

Set stores a JSON-serialisable value (a form model, view state) under key for the next request.

func (*FlashCtx) Success added in v0.39.0

func (f *FlashCtx) Success(text string)

Success message for the next request.

func (*FlashCtx) Successes added in v0.39.0

func (f *FlashCtx) Successes() []string

Successes returns the success messages for this request.

func (*FlashCtx) Warning added in v0.39.0

func (f *FlashCtx) Warning(text string)

Warning message for the next request.

func (*FlashCtx) Warnings added in v0.39.0

func (f *FlashCtx) Warnings() []string

Warnings returns the warning messages for this request.

type FormCtx

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

FormCtx represents the post form key-value pairs.

func (*FormCtx) Bool

func (f *FormCtx) Bool(key string) (bool, error)

Bool returns the value of the parameter as bool.

Valid values ar "true", "false", "1" and "0".

func (*FormCtx) BoolOptional

func (f *FormCtx) BoolOptional(key string) (*bool, error)

BoolOptional returns the value of the parameter as optional bool or null if value is empty.

Valid values ar "true", "false", "1" and "0".

func (*FormCtx) File

func (f *FormCtx) File(key string) (*multipart.FileHeader, error)

File returns uploaded file data.

func (*FormCtx) FileOptional

func (f *FormCtx) FileOptional(key string) *multipart.FileHeader

FileOptional returns uploaded file data if it's provided.

func (*FormCtx) Files

func (f *FormCtx) Files(key string) []*multipart.FileHeader

Files returns uploaded files.

func (*FormCtx) Int

func (f *FormCtx) Int(key string) (int, error)

Int returns the value of the parameter as int.

func (*FormCtx) Int64

func (f *FormCtx) Int64(key string) (int64, error)

Int64 returns the value of the parameter as int64.

func (*FormCtx) Int64Optional

func (f *FormCtx) Int64Optional(key string) (*int64, error)

Int64Optional returns the value of the parameter as optional int64 or null if value is empty.

func (*FormCtx) IntOptional

func (f *FormCtx) IntOptional(key string) (*int, error)

IntOptional returns the value of the parameter as optional int or null if value is empty.

func (*FormCtx) String

func (f *FormCtx) String(key string) (string, error)

String gets the first value associated with the given key in form. If there are no values associated with the key or value is empty returns ParamRequiredError error.

func (*FormCtx) StringOptional

func (f *FormCtx) StringOptional(key string) *string

StringOptional gets the first value associated with the given key in query or null if value is empty.

func (*FormCtx) Values

func (f *FormCtx) Values(key string) []string

Values returns all values associated with the given key in query.

type Handler

type Handler interface {
	Handler(ctx *Context)
}

Handler is an adapter to process incoming requests using object method.

type HeaderCtx

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

HeaderCtx represents the key-value pairs in an HTTP header.

func (*HeaderCtx) AcceptsEncoding added in v0.35.0

func (h *HeaderCtx) AcceptsEncoding(encoding string) bool

AcceptsEncoding returns true if the request accepts the given content encoding.

func (*HeaderCtx) Add

func (h *HeaderCtx) Add(key, value string)

Add adds the key, value pair to the response header. It appends to any existing values associated with key.

func (*HeaderCtx) All added in v0.35.0

func (h *HeaderCtx) All() iter.Seq2[string, string]

All returns an iterator over all request header entries.

func (*HeaderCtx) AllInOrder added in v0.35.0

func (h *HeaderCtx) AllInOrder() iter.Seq2[string, string]

AllInOrder returns an iterator over all request header entries in the order they were received.

It is slightly slower than All because it has to reparse the raw headers to get the order.

func (*HeaderCtx) AppendAccessControlExposeHeaders

func (h *HeaderCtx) AppendAccessControlExposeHeaders(names ...string)

AppendAccessControlExposeHeaders appends the given headers to the Access-Control-Expose-Headers header.

func (*HeaderCtx) Del

func (h *HeaderCtx) Del(key string)

Del deletes the values associated with key in both request and response.

func (*HeaderCtx) Get

func (h *HeaderCtx) Get(key string) string

Get gets the first value associated with the given key in request. If there are no values associated with the key, Get returns "".

func (*HeaderCtx) InheritAuthorization added in v0.17.1

func (h *HeaderCtx) InheritAuthorization() http.RequestOption

InheritAuthorization returns HTTP client request option with inherited authorization from request.

func (*HeaderCtx) Keys added in v0.16.0

func (h *HeaderCtx) Keys() iter.Seq[string]

Keys returns an iterator over all header keys in request.

func (*HeaderCtx) Set

func (h *HeaderCtx) Set(key, value string)

Set sets the response header entries associated with key to the single element value. It replaces any existing values associated with key.

func (*HeaderCtx) SetAlways added in v0.33.0

func (h *HeaderCtx) SetAlways(key, value string)

SetAlways sets the response header like Set, and additionally re-applies it if the response is later reset to render an error. Use it for headers that must remain on error responses, such as CORS headers.

func (*HeaderCtx) Values

func (h *HeaderCtx) Values(key string) []string

Values returns all values associated with the given key in request.

type MetricsOptions

type MetricsOptions struct {
	TrustedSource

	// SkipPaths represents paths to bypass metrics handler.
	SkipPaths []string
}

MetricsOptions configures the metrics endpoint.

type ParamInvalidError added in v0.13.0

type ParamInvalidError struct {
	Name string
	Tag  string
	Err  error
}

ParamInvalidError is an error that occurs when a parameter is invalid.

func (ParamInvalidError) Error added in v0.13.0

func (e ParamInvalidError) Error() string

func (ParamInvalidError) SafeError added in v0.13.0

func (e ParamInvalidError) SafeError() string

SafeError returns a safe error message for ParamInvalidError.

func (ParamInvalidError) StatusCode added in v0.13.0

func (ParamInvalidError) StatusCode() int

StatusCode returns the HTTP status code for ParamInvalidError.

type ParamRequiredError added in v0.13.0

type ParamRequiredError struct {
	Name string
}

ParamRequiredError is an error that occurs when a required parameter is not provided.

func (ParamRequiredError) Error added in v0.13.0

func (e ParamRequiredError) Error() string

func (ParamRequiredError) SafeError added in v0.13.0

func (e ParamRequiredError) SafeError() string

SafeError returns a safe error message for ParamRequiredError.

func (ParamRequiredError) StatusCode added in v0.13.0

func (ParamRequiredError) StatusCode() int

StatusCode returns the HTTP status code for ParamRequiredError.

type ParamsCtx

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

ParamsCtx represents the parameters of route URL.

func (*ParamsCtx) Has added in v0.11.0

func (p *ParamsCtx) Has(key string) bool

Has the given name specified in route params.

func (*ParamsCtx) Int

func (p *ParamsCtx) Int(key string) (int, error)

Int returns the value of the parameter as int.

func (*ParamsCtx) Int64

func (p *ParamsCtx) Int64(key string) (int64, error)

Int64 returns the value of the parameter as int64.

func (*ParamsCtx) String

func (p *ParamsCtx) String(key string) string

String gets the first value associated with the given name in route params.

type Proxy

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

Proxy is the proxy handler.

func (*Proxy) Handler

func (p *Proxy) Handler(ctx *Context)

Handler implements azugo.Handler to handle incoming request.

type ProxyOption

type ProxyOption interface {
	// contains filtered or unexported methods
}

ProxyOption is a proxy option.

func ProxyUpstream

func ProxyUpstream(upstream ...*url.URL) ProxyOption

ProxyUpstream adds one or more upstream URLs.

func ProxyUpstreamBodyReplaceText

func ProxyUpstreamBodyReplaceText(from, to string) ProxyOption

ProxyUpstreamBodyReplaceText replaces text in the response body.

type ProxyOptions

type ProxyOptions struct {
	// ForwardLimit limits the number of entries in the headers that will be processed.
	// The default value is 1. Set to 0 to disable the limit.
	// Trusting all entries in the headers is a security risk.
	ForwardLimit int
	// TrustAll option sets to trust all proxies.
	TrustAll bool
	// TrustedIPs represents addresses of trusted proxies.
	TrustedIPs []net.IP
	// TrustedNetworks represents addresses of trusted networks.
	TrustedNetworks []*net.IPNet
	// TrustedHeaders represents headers that contain the client's real IP address and their preference.
	TrustedHeaders []string
}

ProxyOptions configures a reverse proxy upstream.

func (*ProxyOptions) Add

func (opts *ProxyOptions) Add(ipnet string)

Add proxy IP or network in CIDR format to trusted proxy list. Specify "*" to trust all proxies.

func (*ProxyOptions) Clear

func (opts *ProxyOptions) Clear()

Clear clears trusted proxy list.

type ProxyUpstreamBodyReplaceURL

type ProxyUpstreamBodyReplaceURL bool

ProxyUpstreamBodyReplaceURL replaces URL in the response body.

type ProxyUpstreamInsecureSkipVerify

type ProxyUpstreamInsecureSkipVerify bool

ProxyUpstreamInsecureSkipVerify skips TLS certificate verification for upstream request.

type QueryCtx

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

QueryCtx represents the key-value pairs in an query string.

func (*QueryCtx) Bool

func (q *QueryCtx) Bool(key string) (bool, error)

Bool returns the value of the parameter as bool.

Valid values ar "true", "false", "1" and "0".

func (*QueryCtx) BoolOptional

func (q *QueryCtx) BoolOptional(key string) (*bool, error)

BoolOptional returns the value of the parameter as optional bool or null if value is empty.

Valid values ar "true", "false", "1" and "0".

func (*QueryCtx) Int

func (q *QueryCtx) Int(key string) (int, error)

Int returns the value of the parameter as int.

func (*QueryCtx) Int64

func (q *QueryCtx) Int64(key string) (int64, error)

Int64 returns the value of the parameter as int64.

func (*QueryCtx) Int64Optional

func (q *QueryCtx) Int64Optional(key string) (*int64, error)

Int64Optional returns the value of the parameter as optional int64 or null if value is empty.

func (*QueryCtx) IntOptional

func (q *QueryCtx) IntOptional(key string) (*int, error)

IntOptional returns the value of the parameter as optional int or null if value is empty.

func (*QueryCtx) Raw added in v0.35.0

func (q *QueryCtx) Raw() string

Raw returns the raw query string part of the request URL.

func (*QueryCtx) String

func (q *QueryCtx) String(key string) (string, error)

String gets the first value associated with the given key in query. If there are no values associated with the key or value is empty returns ParamRequiredError error.

func (*QueryCtx) StringOptional

func (q *QueryCtx) StringOptional(key string) *string

StringOptional gets the first value associated with the given key in query or null if value is empty.

func (*QueryCtx) Values

func (q *QueryCtx) Values(key string) []string

Values returns all values associated with the given key in query.

type RequestHandler

type RequestHandler func(ctx *Context)

RequestHandler must process incoming requests.

RequestHandler must call ctx.TimeoutError() before returning if it keeps references to ctx and/or its' members after the return. Consider wrapping RequestHandler into TimeoutHandler if response time must be limited.

func Handle

func Handle(h Handler) RequestHandler

Handle allows to use object method that implements Handler interface to handle incoming requests.

type RequestHandlerFunc

type RequestHandlerFunc func(h RequestHandler) RequestHandler

RequestHandlerFunc is an adapter to allow to use it as wrapper for RequestHandler.

type RouteGroup

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

RouteGroup is a sub-router to group paths.

func (*RouteGroup) Any

func (g *RouteGroup) Any(path string, handler RequestHandler)

Any is a shortcut for all HTTP methods handler

WARNING: Use only for routes where the request method is not important.

func (*RouteGroup) Connect

func (g *RouteGroup) Connect(path string, handler RequestHandler)

Connect is a shortcut for HTTP CONNECT method handler.

func (*RouteGroup) Delete

func (g *RouteGroup) Delete(path string, handler RequestHandler)

Delete is a shortcut for HTTP DELETE method handler.

func (*RouteGroup) Get

func (g *RouteGroup) Get(path string, handler RequestHandler)

Get is a shortcut for HTTP GET method handler.

func (*RouteGroup) Group

func (g *RouteGroup) Group(path string) Router

Group returns a new group. Path auto-correction, including trailing slashes, is enabled by default.

func (*RouteGroup) Handle

func (g *RouteGroup) Handle(method http.Method, path string, handler RequestHandler)

Handle registers a new request handler with the given path and method.

For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*RouteGroup) Head

func (g *RouteGroup) Head(path string, handler RequestHandler)

Head is a shortcut for HTTP HEAD method handler.

func (*RouteGroup) Mutable added in v0.5.0

func (g *RouteGroup) Mutable(v bool)

Mutable allows updating the route handler. Sets for all router not only for group.

Disabled by default. WARNING: Use with care. It could generate unexpected behaviors.

func (*RouteGroup) Options

func (g *RouteGroup) Options(path string, handler RequestHandler)

Options is a shortcut for HTTP OPTIONS method handler.

func (*RouteGroup) Patch

func (g *RouteGroup) Patch(path string, handler RequestHandler)

Patch is a shortcut for HTTP PATCH method handler.

func (*RouteGroup) Post

func (g *RouteGroup) Post(path string, handler RequestHandler)

Post is a shortcut for HTTP POST method handler.

func (*RouteGroup) Proxy

func (g *RouteGroup) Proxy(path string, options ...ProxyOption)

Proxy is helper to proxy requests to another host.

func (*RouteGroup) Put

func (g *RouteGroup) Put(path string, handler RequestHandler)

Put is a shortcut for HTTP PUT method handler.

func (*RouteGroup) Query added in v0.35.0

func (g *RouteGroup) Query(path string, handler RequestHandler)

Query is a shortcut for HTTP QUERY method handler.

func (*RouteGroup) Trace

func (g *RouteGroup) Trace(path string, handler RequestHandler)

Trace is a shortcut for HTTP TRACE method handler.

func (*RouteGroup) Use

func (g *RouteGroup) Use(middleware ...RequestHandlerFunc)

Use appends a middleware to the specified route group. Middlewares will be executed in the order they were added. It will be executed only for the routes that have been added after the middleware was registered.

type RouteSwitcher added in v0.5.0

type RouteSwitcher interface {
	// SelectRouter returns a router based on the request.
	//
	// To fallback to default App router return nil.
	SelectRouter(ctx *fasthttp.RequestCtx) RouterHandler
}

RouteSwitcher is used to select a router for a request.

type Router added in v0.5.0

type Router interface {
	// Mutable allows updating the route handler.
	//
	// Disabled by default.
	// WARNING: Use with care. It could generate unexpected behaviors
	Mutable(v bool)

	// Group returns a new group.
	// Path auto-correction, including trailing slashes, is enabled by default.
	Group(path string) Router

	// Use appends a middleware to the router.
	// Middlewares will be executed in the order they were added.
	// It will be executed only for the routes that have been
	// added after the middleware was registered.
	Use(middlewares ...RequestHandlerFunc)

	// Handle registers a new request handler with the given path and method.
	//
	// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
	// functions can be used.
	//
	// This function is intended for bulk loading and to allow the usage of less
	// frequently used, non-standardized or custom methods (e.g. for internal
	// communication with a proxy).
	Handle(method http.Method, path string, handler RequestHandler)

	// Get is a shortcut for HTTP GET method handler.
	Get(path string, handler RequestHandler)

	// Head is a shortcut for HTTP HEAD method handler.
	Head(path string, handler RequestHandler)

	// Query is a shortcut for HTTP QUERY method handler.
	Query(path string, handler RequestHandler)

	// Post is a shortcut for HTTP POST method handler.
	Post(path string, handler RequestHandler)

	// Put is a shortcut for HTTP PUT method handler.
	Put(path string, handler RequestHandler)

	// Patch is a shortcut for HTTP PATCH method handler.
	Patch(path string, handler RequestHandler)

	// Delete is a shortcut for HTTP DELETE method handler.
	Delete(path string, handler RequestHandler)

	// Connect is a shortcut for HTTP CONNECT method handler.
	Connect(path string, handler RequestHandler)

	// Options is a shortcut for HTTP OPTIONS method handler.
	Options(path string, handler RequestHandler)

	// Trace is a shortcut for HTTP TRACE method handler.
	Trace(path string, handler RequestHandler)

	// Proxy is helper to proxy requests to another host.
	Proxy(path string, options ...ProxyOption)

	// Any is a shortcut for all HTTP methods handler.
	//
	// WARNING: Use only for routes where the request method is not important.
	Any(path string, handler RequestHandler)
}

Router to handle multiple methods.

type RouterHandler added in v0.5.0

type RouterHandler interface {
	Router

	// Handler for processing incoming requests.
	Handler(ctx *fasthttp.RequestCtx)
}

RouterHandler is the interface for registering and serving routes.

func NewRouter added in v0.5.0

func NewRouter(app *App) RouterHandler

NewRouter creates a new RouterHandler for the given app.

type RouterOptions

type RouterOptions struct {
	// Proxy is the options to describe the trusted proxies.
	Proxy ProxyOptions

	// CorsOptions is the options to describe Cross-Origin Resource Sharing (CORS)
	CORS CORSOptions

	// Host is the hostname to be used for URL generation. If not set
	// it will be automatically detected from the request.
	Host string

	// BasePath is the base path of the router.
	BasePath string

	// Enables automatic redirection if the current route can't be matched but a
	// handler for the path with (without) the trailing slash exists.
	// For example if /foo/ is requested but a route only exists for /foo, the
	// client is redirected to /foo with http status code 301 for GET requests
	// and 308 for all other request methods.
	RedirectTrailingSlash bool

	// If enabled, the router tries to fix the current request path, if no
	// handle is registered for it.
	// First superfluous path elements like ../ or // are removed.
	// Afterwards the router does a case-insensitive lookup of the cleaned path.
	// If a handle can be found for this route, the router makes a redirection
	// to the corrected path with status code 301 for GET requests and 308 for
	// all other request methods.
	// For example /FOO and /..//Foo could be redirected to /foo.
	// RedirectTrailingSlash is independent of this option.
	RedirectFixedPath bool

	// If enabled, the router checks if another method is allowed for the
	// current route, if the current request can not be routed.
	// If this is the case, the request is answered with 'Method Not Allowed'
	// and HTTP status code 405.
	// If no other Method is allowed, the request is delegated to the NotFound
	// handler.
	HandleMethodNotAllowed bool

	// If enabled, the router automatically replies to OPTIONS requests.
	// Custom OPTIONS handlers take priority over automatic replies.
	HandleOPTIONS bool

	// An optional RequestHandler that is called on automatic OPTIONS requests.
	// The handler is only called if HandleOPTIONS is true and no OPTIONS
	// handler for the specific path was set.
	// The "Allowed" header is set before calling the handler.
	GlobalOPTIONS RequestHandler

	// Configurable RequestHandler which is called when no matching route is
	// found. If it is not set, default NotFound is used.
	NotFound RequestHandler

	// Configurable RequestHandler which is called when a request
	// cannot be routed and HandleMethodNotAllowed is true.
	// If it is not set, http.StatusMethodNotAllowed will be returned.
	// The "Allow" header with allowed request methods is set before the handler
	// is called.
	MethodNotAllowed RequestHandler

	// Configurable http handler that will be called when there is an error.
	// It will be automatically called if any of the Azugo helper response methods
	// encounters an error.
	// If it is not set, error message will be returned for errors that implement
	// SafeError interface, otherwise error will be logged and http error code
	// 500 (Internal Server Error) will be returned.
	// Should return true if the error was handled, false otherwise that default
	// error handling should be applied.
	ErrorHandler func(*Context, error) bool
}

RouterOptions allow to configure the router behavior.

func (*RouterOptions) ApplyConfig added in v0.5.0

func (r *RouterOptions) ApplyConfig(conf *config.Configuration)

ApplyConfig applies router-related configuration options.

type SafeError

type SafeError interface {
	SafeError() string
}

SafeError is an interface that error can implement to return message that can be safely returned to the client.

type ServerOptions

type ServerOptions struct {
	// Per-connection buffer size for requests' reading.
	// This also limits the maximum header size.
	//
	// Increase this buffer if your clients send multi-KB RequestURIs
	// and/or multi-KB headers (for example, BIG cookies).
	//
	// Default buffer size 8K is used if not set.
	RequestReadBufferSize int

	// Per-connection buffer size for responses' writing.
	//
	// Default buffer size 8K is used if not set.
	ResponseWriteBufferSize int
}

ServerOptions configures the HTTP server buffer sizes.

type StaticContentReplacer added in v0.24.0

type StaticContentReplacer func(ctx *Context) (string, *strings.Replacer)

StaticContentReplacer is a function that will be called to replace values in the content of all files. First return value is the hash to use for caching, second return value is the replacer. If empty string is returned for the hash, the content will not be cached.

type StaticDirTrimPrefix added in v0.16.0

type StaticDirTrimPrefix string

StaticDirTrimPrefix sets the prefix to trim from the FS path.

type StaticOption added in v0.16.0

type StaticOption interface {
	// contains filtered or unexported methods
}

StaticOption is an interface for static file serving options.

func StaticGzipContent added in v0.33.0

func StaticGzipContent() StaticOption

StaticGzipContent enables pre-compressed gzip content that is served directly when the client accepts gzip encoding.

type StaticSPARouterPath added in v0.25.2

type StaticSPARouterPath string

StaticSPARouterPath sets the path to use for all unknown static content paths for SPA routing.

type TestApp

type TestApp struct {
	*App
	// contains filtered or unexported fields
}

TestApp represents testing app instance.

func NewTestApp

func NewTestApp(app ...*App) *TestApp

NewTestApp creates new testing application instance.

func (*TestApp) MockContext added in v0.20.3

func (a *TestApp) MockContext(fn RequestHandler)

MockContext creates new mock context for testing.

func (*TestApp) Start

func (a *TestApp) Start(t *testing.T)

Start starts testing web server instance.

func (*TestApp) StartBenchmark

func (a *TestApp) StartBenchmark()

StartBenchmark starts benchmarking web server instance.

func (*TestApp) Stop

func (a *TestApp) Stop()

Stop web server instance.

func (*TestApp) TestClient

func (a *TestApp) TestClient() *TestClient

TestClient returns testing client that will do HTTP requests to test web server.

type TestClient

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

TestClient is a test client for testing purposes.

func (*TestClient) Call

func (c *TestClient) Call(method http.Method, endpoint string, body []byte, options ...TestClientOption) (*fasthttp.Response, error)

Call calls the given method and endpoint with the given body and options.

func (*TestClient) CallRaw

func (c *TestClient) CallRaw(method, endpoint, body []byte, options ...TestClientOption) (*fasthttp.Response, error)

CallRaw calls the given method and endpoint with the given body and options.

func (*TestClient) ClearCookies added in v0.33.0

func (c *TestClient) ClearCookies()

ClearCookies removes all cookies from the jar.

func (*TestClient) Client added in v0.7.0

func (c *TestClient) Client() *fasthttp.Client

Client returns the underlying fasthttp client.

func (*TestClient) Connect

func (c *TestClient) Connect(endpoint string, options ...TestClientOption) (*fasthttp.Response, error)

Connect calls CONNECT method with given options.

func (*TestClient) Cookies added in v0.33.0

func (c *TestClient) Cookies() map[string]string

Cookies returns a copy of all cookies currently held in the jar.

func (*TestClient) Delete

func (c *TestClient) Delete(endpoint string, options ...TestClientOption) (*fasthttp.Response, error)

Delete calls DELETE method with given options.

func (*TestClient) Get

func (c *TestClient) Get(endpoint string, options ...TestClientOption) (*fasthttp.Response, error)

Get calls GET method with given options.

func (*TestClient) Head

func (c *TestClient) Head(endpoint string, options ...TestClientOption) (*fasthttp.Response, error)

Head calls HEAD method with given options.

func (*TestClient) Options

func (c *TestClient) Options(endpoint string, options ...TestClientOption) (*fasthttp.Response, error)

Options calls OPTIONS method with given options.

func (*TestClient) Patch

func (c *TestClient) Patch(endpoint string, body []byte, options ...TestClientOption) (*fasthttp.Response, error)

Patch calls PATCH method with given body and options.

func (*TestClient) PatchForm

func (c *TestClient) PatchForm(endpoint string, params map[string]any, options ...TestClientOption) (*fasthttp.Response, error)

PatchForm calls PATCH method with given map marshaled as URL encoded form and options.

func (*TestClient) PatchJSON

func (c *TestClient) PatchJSON(endpoint string, body any, options ...TestClientOption) (*fasthttp.Response, error)

PatchJSON calls PATCH method with given object marshaled as JSON and options.

func (*TestClient) PatchMultiPartForm

func (c *TestClient) PatchMultiPartForm(endpoint string, form *multipart.Form, options ...TestClientOption) (*fasthttp.Response, error)

PatchMultiPartForm calls PATCH method with given multipart form and options.

func (*TestClient) Post

func (c *TestClient) Post(endpoint string, body []byte, options ...TestClientOption) (*fasthttp.Response, error)

Post calls POST method with given body and options.

func (*TestClient) PostForm

func (c *TestClient) PostForm(endpoint string, params map[string]any, options ...TestClientOption) (*fasthttp.Response, error)

PostForm calls POST method with given map marshaled as URL encoded form and options.

func (*TestClient) PostJSON

func (c *TestClient) PostJSON(endpoint string, body any, options ...TestClientOption) (*fasthttp.Response, error)

PostJSON calls POST method with given object marshaled as JSON and options.

func (*TestClient) PostMultiPartForm

func (c *TestClient) PostMultiPartForm(endpoint string, form *multipart.Form, options ...TestClientOption) (*fasthttp.Response, error)

PostMultiPartForm calls POST method with given multipart form and options.

func (*TestClient) Put

func (c *TestClient) Put(endpoint string, body []byte, options ...TestClientOption) (*fasthttp.Response, error)

Put calls PUT method with given body and options.

func (*TestClient) PutForm

func (c *TestClient) PutForm(endpoint string, params map[string]any, options ...TestClientOption) (*fasthttp.Response, error)

PutForm calls PUT method with given map marshaled as URL encoded form and options.

func (*TestClient) PutJSON

func (c *TestClient) PutJSON(endpoint string, body any, options ...TestClientOption) (*fasthttp.Response, error)

PutJSON calls PUT method with given object marshaled as JSON and options.

func (*TestClient) PutMultiPartForm

func (c *TestClient) PutMultiPartForm(endpoint string, form *multipart.Form, options ...TestClientOption) (*fasthttp.Response, error)

PutMultiPartForm calls PUT method with given multipart form and options.

func (*TestClient) Query added in v0.35.0

func (c *TestClient) Query(endpoint string, body []byte, options ...TestClientOption) (*fasthttp.Response, error)

Query calls QUERY method with given body and options.

func (*TestClient) QueryForm added in v0.35.0

func (c *TestClient) QueryForm(endpoint string, params map[string]any, options ...TestClientOption) (*fasthttp.Response, error)

QueryForm calls QUERY method with given map marshaled as URL encoded form and options.

func (*TestClient) QueryJSON added in v0.35.0

func (c *TestClient) QueryJSON(endpoint string, body any, options ...TestClientOption) (*fasthttp.Response, error)

QueryJSON calls QUERY method with given object marshaled as JSON and options.

func (*TestClient) Trace

func (c *TestClient) Trace(endpoint string, options ...TestClientOption) (*fasthttp.Response, error)

Trace calls TRACE method with given options.

func (*TestClient) WithCookie added in v0.33.0

func (c *TestClient) WithCookie(name, value string) TestClientOption

WithCookie adds a cookie to the request, overriding any jar cookie with the same name.

func (*TestClient) WithHeader

func (c *TestClient) WithHeader(key, value string) TestClientOption

WithHeader adds header to request.

func (*TestClient) WithHost added in v0.5.0

func (c *TestClient) WithHost(host string) TestClientOption

WithHost sets host for the request.

func (*TestClient) WithMultiPartFormBoundary

func (c *TestClient) WithMultiPartFormBoundary(boundary string) TestClientOption

WithMultiPartFormBoundary sets multipart form data boundary.

func (*TestClient) WithQuery

func (c *TestClient) WithQuery(params map[string]any) TestClientOption

WithQuery adds query parameters from map to query arguments.

type TestClientOption

type TestClientOption func(*TestClient, *fasthttp.Request)

TestClientOption is a test client option.

type TrustedSource added in v0.31.0

type TrustedSource struct {
	// TrustAll trusts all IP addresses.
	TrustAll bool
	// TrustedIPs is the list of trusted IP addresses.
	TrustedIPs []net.IP
	// TrustedNetworks is the list of trusted networks.
	TrustedNetworks []*net.IPNet
}

TrustedSource holds a list of trusted IP addresses and networks and reports whether a given IP is among them.

func (*TrustedSource) Add added in v0.31.0

func (t *TrustedSource) Add(ipnet string) *TrustedSource

Add adds an IP address or CIDR network to the trusted list. Specify "*" to trust all sources.

func (*TrustedSource) Clear added in v0.31.0

func (t *TrustedSource) Clear() *TrustedSource

Clear resets all trusted entries.

func (*TrustedSource) IsTrusted added in v0.31.0

func (t *TrustedSource) IsTrusted(ip net.IP) bool

IsTrusted reports whether the given IP is in the trusted list.

type User

type User interface {
	UserAuthorizer
	UserDisplayNamer
	UserGrantedScopes
	UserClaimer

	// ID returns user ID.
	ID() string
}

User is an interface that provides methods to get user information.

type UserAuthorizer added in v0.6.0

type UserAuthorizer interface {
	// Authorized returns if user is authorized.
	Authorized() bool
}

UserAuthorizer is an interface to check if user is authorized.

type UserClaimer

type UserClaimer interface {
	// Claim returns user claim with all values.
	Claim(name ...string) token.ClaimStrings
	// ClaimValue returns user claim with first value.
	ClaimValue(name ...string) string
}

UserClaimer is an interface that provides methods to get user claims.

type UserDisplayNamer

type UserDisplayNamer interface {
	// GivenName returns users given name.
	GivenName() string
	// FamilyName returns users family name.
	FamilyName() string
	// DisplayName returns user display name.
	DisplayName() string
}

UserDisplayNamer is an interface that provides method for user display name.

type UserGrantedScopes added in v0.6.0

type UserGrantedScopes interface {
	// HasScopeGroup checks if user has any granted scopes in specified group.
	HasScopeGroup(name string) bool
	// HasScope checks if user has granted scope with any level.
	HasScope(name string) bool
	// HasScopeLevel checks if user has granted scope with exact level.
	HasScopeLevel(name string, level string) bool
	// HasScopeAnyLevel checks if user has granted scope with one of levels.
	HasScopeAnyLevel(name string, levels ...string) bool
}

UserGrantedScopes is an interface that provides methods to check user granted scopes.

type Validator

type Validator interface {
	// Validate validates the struct and returns validation error.
	Validate(ctx *Context) error
}

Validator is an interface that can be implemented by structs that can be called to validate the struct.

Directories

Path Synopsis
Package config provides application configuration types and helpers.
Package config provides application configuration types and helpers.
Package healthz provides a health check endpoint handler following the IETF Health Check Response Format for HTTP APIs draft specification.
Package healthz provides a health check endpoint handler following the IETF Health Check Response Format for HTTP APIs draft specification.
internal
proxy
Package proxy provides internal HTTP proxy utilities.
Package proxy provides internal HTTP proxy utilities.
radix
Package radix provides a radix tree implementation for HTTP routing.
Package radix provides a radix tree implementation for HTTP routing.
router
Package router provides internal HTTP routing helpers.
Package router provides internal HTTP routing helpers.
utils
Package utils provides internal utility helpers.
Package utils provides internal utility helpers.
wsfed
Package wsfed provides WS-Federation metadata parsing.
Package wsfed provides WS-Federation metadata parsing.
Package middleware provides HTTP middleware for the azugo framework.
Package middleware provides HTTP middleware for the azugo framework.
Package server provides server start and health check commands.
Package server provides server start and health check commands.
Package token provides JWT claim types and helpers.
Package token provides JWT claim types and helpers.
nonce
Package nonce provides nonce store implementations for WS-Federation.
Package nonce provides nonce store implementations for WS-Federation.
Package user provides user identity types and helpers.
Package user provides user identity types and helpers.
Package wsfed provides WS-Federation authentication support.
Package wsfed provides WS-Federation authentication support.

Jump to

Keyboard shortcuts

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