azugo

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2023 License: MIT Imports: 39 Imported by: 2

README

azugo

Opinionated GoLang web framework for microservices based on FastHTTP.

Features
Special Environment variables used by the Azugo framework
  • ENVIRONMENT - An App environment setting (allowed values are Development, Staging and Production).
  • BASE_PATH - Base path for an App if it's deployed in subdirectory.
  • SERVER_URLS - An server URL or multiple URLS separated by semicolon to listen on.
  • ACCESS_LOG_ENABLED - Option to enable access logs (defaults to true).
Special thanks to

Documentation

Index

Constants

View Source
const (
	HeaderAccept                     string = "Accept"
	HeaderTotalCount                 string = "X-Total-Count"
	HeaderLink                       string = "Link"
	HeaderAccessControlExposeHeaders string = "Access-Control-Expose-Headers"
	HeaderContentType                string = "Content-Type"
	HeaderContentDisposition         string = "Content-Disposition"
	HeaderContentTransferEncoding    string = "Content-Transfer-Encoding"
)
View Source
const (
	ContentTypeJSON        string = "application/json"
	ContentTypeXML         string = "application/xml"
	ContentTypeOctetStream string = "application/octet-stream"
)
View Source
const DefaultMetricPath string = "/metrics"
View Source
const InstrumentationRequest = "http-request"
View Source
const MethodWild = "*"

MethodWild wild HTTP method

Variables

This section is empty.

Functions

This section is empty.

Types

type App

type App struct {
	*core.App

	// Metrics options
	MetricsOptions MetricsOptions

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

func New

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

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

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

func (a *App) Handle(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) RouterOptions

func (a *App) RouterOptions() *RouterOptions

RouterOptions for default router.

func (*App) Routes

func (a *App) Routes() map[string][]string

Routes returns all registered routes grouped by method

func (*App) SetConfig

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

SetConfig binds application configuration to the application.

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

type BadRequestError added in v0.13.0

type BadRequestError struct {
	Description string
}

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) StatusCode added in v0.13.0

func (e BadRequestError) StatusCode() int

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

Copy copies the request raw body to the provided writer.

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

ValidOrigins returns true if CORS origin is allowed.

type Context

type Context struct {

	// Header access methods
	Header HeaderCtx
	// 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
}

func (*Context) Accepts

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

Accepts checks if provided content type is acceptable for client.

func (*Context) AcceptsExplicit

func (ctx *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 (ctx *Context) AddLogFields(fields ...zap.Field) error

AddLogFields add fields to context logger.

func (*Context) App

func (ctx *Context) App() *App

App returns the application.

func (*Context) BasePath

func (ctx *Context) BasePath() string

BasePath returns the base path.

func (*Context) BaseURL

func (ctx *Context) BaseURL() string

BaseURL returns the base URL for the request.

func (*Context) ContentType

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

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

func (*Context) Context

func (ctx *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() (deadline time.Time, ok 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's closed when work done on behalf of this context should be canceled. Done may return nil if this context can never be canceled. Successive calls to Done return the same value. The close of the Done channel may happen asynchronously, after the cancel function returns.

WithCancel arranges for Done to be closed when cancel is called; WithDeadline arranges for Done to be closed when the deadline expires; WithTimeout arranges for Done to be closed when the timeout elapses.

Done is provided for use in select statements:

// Stream generates values with DoSomething and sends them to out
// until DoSomething returns an error or ctx.Done is closed.
func Stream(ctx context.Context, out chan<- Value) error {
	for {
		v, err := DoSomething(ctx)
		if err != nil {
			return err
		}
		select {
		case <-ctx.Done():
			return ctx.Err()
		case out <- v:
		}
	}
}

See https://blog.golang.org/pipelines for more examples of how to use a Done channel for cancellation.

func (*Context) Env

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

Env returns the application environment.

func (*Context) Err

func (c *Context) Err() error

If Done is not yet closed, Err returns nil. If Done is closed, Err returns a non-nil error explaining why: Canceled if the context was canceled or DeadlineExceeded if the context's deadline passed. After Err returns a non-nil error, successive calls to Err return the same error.

func (*Context) Error

func (ctx *Context) Error(err error)

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

func (*Context) Host

func (ctx *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 (ctx *Context) ID() string

ID returns the unique request identifier.

func (*Context) IP

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

IP returns the client's network IP address.

func (*Context) IsTLS

func (ctx *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 (ctx *Context) IsTrustedProxy() bool

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

func (*Context) JSON

func (ctx *Context) JSON(obj any)

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

func (*Context) Log

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

Log returns the logger.

func (*Context) Method

func (ctx *Context) Method() string

Method returns the request method.

func (*Context) NotFound

func (ctx *Context) NotFound()

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

func (*Context) Paging

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

Returns Paginator with page size from query parameters

func (*Context) Path

func (ctx *Context) Path() string

Path returns the path part of the request URL.

func (*Context) Raw

func (ctx *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 (ctx *Context) Redirect(url string)

Redirect redirects the request to a given URL with status code 302 (Found) if other redirect status code not set already.

func (*Context) ReplaceLogger added in v0.8.0

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

ReplaceLogger replaces current context logger with custom.

func (*Context) Request

func (ctx *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 (ctx *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 (ctx *Context) RouterOptions() *RouterOptions

RouterOptions returns the router options.

func (*Context) RouterPath

func (ctx *Context) RouterPath() string

RouterPath returns the registered router path.

func (*Context) SetPaging

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

func (*Context) SetUser

func (ctx *Context) SetUser(u User)

SetUser sets authorized user.

func (*Context) SetUserValue

func (ctx *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) SkipRequestLog added in v0.8.0

func (ctx *Context) SkipRequestLog()

SkipRequestLog sets to skip request log entry for current request.

func (*Context) StatusCode

func (ctx *Context) StatusCode(status int) *Context

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

func (*Context) Text

func (ctx *Context) Text(text string)

Text sets the response body to the given text.

func (*Context) User

func (ctx *Context) User() User

User returns authorized user or

func (*Context) UserAgent

func (ctx *Context) UserAgent() string

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

func (*Context) UserValue

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

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

func (*Context) Validate

func (ctx *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 ErrorResponse

type ErrorResponse struct {
	Errors []*ErrorResponseError `json:"errors" xml:"Errors>Error"`
}

ErrorResponse represents an error response.

func NewErrorResponse

func NewErrorResponse(err error) *ErrorResponse

NewErrorResponse creates an error response from the given error.

type ErrorResponseError

type ErrorResponseError struct {
	Type    string `json:"type" xml:"Type"`
	Message string `json:"message" xml:"Message"`
}

ErrorResponseError is an error response error details.

type ForbiddenError added in v0.13.0

type ForbiddenError struct{}

ForbiddenError is an error that occurs when user access is denied.

func (ForbiddenError) Error added in v0.13.0

func (e ForbiddenError) Error() string

func (ForbiddenError) StatusCode added in v0.13.0

func (e ForbiddenError) StatusCode() int

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(*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) 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) 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) 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) Values

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

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

type MetricsOptions

type MetricsOptions struct {
	// TrustAll option sets to trust all IP addresses.
	TrustAll bool
	// TrustedIPs represents list of trusted IP addresses.
	TrustedIPs []net.IP
	// TrustedNetworks represents addresses of trusted networks.
	TrustedNetworks []*net.IPNet
	// SkipPaths represents paths to bypass metrics handler
	SkipPaths []string
}

func (*MetricsOptions) Add

func (opts *MetricsOptions) Add(ipnet string) *MetricsOptions

Add IP or network in CIDR format to trusted metrics client list. Specify "*" to trust all sources.

func (*MetricsOptions) Clear

func (opts *MetricsOptions) Clear() *MetricsOptions

Clear trusted metrics client list.

type NotFoundError added in v0.13.0

type NotFoundError struct {
	Resource string
}

NotFoundError is an error that occurs when searched resource is not found.

func (NotFoundError) Error added in v0.13.0

func (e NotFoundError) Error() string

func (NotFoundError) StatusCode added in v0.13.0

func (e NotFoundError) StatusCode() int

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

func (ParamInvalidError) StatusCode added in v0.13.0

func (e ParamInvalidError) StatusCode() int

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

func (ParamRequiredError) StatusCode added in v0.13.0

func (e ParamRequiredError) StatusCode() int

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
}

func (*ProxyOptions) Add

func (opts *ProxyOptions) Add(ipnet string) *ProxyOptions

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

func (*ProxyOptions) Clear

func (opts *ProxyOptions) Clear() *ProxyOptions

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

type ResponseStatusCode interface {
	StatusCode() int
}

ResponseStatusCode is an interface that error can implement to return status code that will be set for the response.

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

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

func NewRouter added in v0.5.0

func NewRouter(app *App) RouterHandler

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, fasthttp.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.
	ErrorHandler func(*Context, error)

	// Function to handle panics recovered from http handlers.
	// It should be used to generate a error page and return the http error code
	// 500 (Internal Server Error).
	// The handler can be used to keep your server from crashing because of
	// unrecovered panics.
	PanicHandler func(*Context, any)
}

RouterOptions allow to configure the router behavior

func (*RouterOptions) ApplyConfig added in v0.5.0

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

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
}

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) 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, 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) 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) 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) Trace

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

Trace calls TRACE method with given options.

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 UnprocessableEntityError added in v0.14.0

type UnprocessableEntityError struct {
	Description string
}

UnprocessableEntityError is an error that occurs when request is well formed, but logically incorrect.

func (UnprocessableEntityError) Error added in v0.14.0

func (e UnprocessableEntityError) Error() string

func (UnprocessableEntityError) StatusCode added in v0.14.0

func (e UnprocessableEntityError) StatusCode() int

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
_examples
api
internal

Jump to

Keyboard shortcuts

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