fiberext

package module
v0.0.0-...-2af90e7 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2026 License: MIT Imports: 7 Imported by: 0

README

██████████ █████ ███████████  ██████████ ███████████      ██████████ █████ █████ ███████████
░░███░░░░░█░░███ ░░███░░░░░███░░███░░░░░█░░███░░░░░███    ░░███░░░░░█░░███ ░░███ ░█░░░███░░░█
 ░███   █ ░  ░███  ░███    ░███ ░███  █ ░  ░███    ░███     ░███  █ ░  ░░███ ███  ░   ░███  ░
 ░███████    ░███  ░██████████  ░██████    ░██████████      ░██████     ░░█████       ░███
 ░███░░░█    ░███  ░███░░░░░███ ░███░░█    ░███░░░░░███     ░███░░█      ███░███      ░███
 ░███  ░     ░███  ░███    ░███ ░███ ░   █ ░███    ░███     ░███ ░   █  ███ ░░███     ░███
 █████       █████ ███████████  ██████████ █████   █████    ██████████ █████ █████    █████
░░░░░       ░░░░░ ░░░░░░░░░░░  ░░░░░░░░░░ ░░░░░   ░░░░░    ░░░░░░░░░░ ░░░░░ ░░░░░    ░░░░░
    

FiberExt - Extension of fiber library to streamline and simplify the development process

Currently under active development and breaking changes are possible

Quick Start

package main

import (
    "context"
    "net/http"

    "github.com/0x626f/fiberext"
)

func main() {
    auth := func(c fiberext.Context) error {
        if c.Get("Authorization") == "" {
            return fiberext.Unauthorized(c)
        }
        return c.Next()
    }

    api := fiberext.NewController("/api/v1").
        AddNewResource(http.MethodGet,  "/users", listUsers).
        AddNewResource(http.MethodPost, "/users", createUser)

    cfg := fiberext.NewConfig().
        WithHost("0.0.0.0").
        WithPort(8080).
        WithDisableStartupMessage(true).
        WithMiddleware(auth).
        WithResource(fiberext.NewResource(http.MethodGet, "/health", healthHandler)).
        WithController(api)

    fiberext.Run(context.Background(), cfg)
}

Reference

Server

server := fiberext.Run(ctx context.Context, cfg *Config) Server

Returns a *fiber.App. Registers middlewares, resources, and controllers in order, then starts the listener in the background. Cancelling ctx triggers graceful shutdown.


Config

cfg := fiberext.NewConfig()

All methods return *Config for chaining.

Method Description
WithHost(string) Bind address (default "")
WithPort(int) Bind port
WithTLS(bool) Enable TLS
WithMutualTLS(bool) Enable mutual TLS
WithCertFile(string) Path to TLS certificate file
WithKeyFile(string) Path to TLS key file
WithClientCertFile(string) Path to client CA file (mTLS)
WithCertificate(tls.Certificate) In-memory TLS certificate
WithClientCerts(*x509.CertPool) In-memory client CA pool (mTLS)
WithMiddleware(Handler) Append a global middleware
WithResource(*Resource) Append a top-level route
WithController(*Controller) Append a route group
WithErrorHandler(ErrorHandler) Custom fiber error handler
WithPrefork(bool) Multi-process listen
WithBodyLimit(int) Max request body size in bytes
WithReadTimeout(time.Duration) Read deadline
WithWriteTimeout(time.Duration) Write deadline
WithIdleTimeout(time.Duration) Keep-alive idle timeout
WithStrictRouting(bool) Treat /foo and /foo/ as different
WithCaseSensitive(bool) Case-sensitive routing
WithDisableStartupMessage(bool) Suppress Fiber banner
WithAppName(string) Application name in headers
WithServerHeader(string) Value of the Server response header
WithJSONEncoder(utils.JSONMarshal) Custom JSON encoder
WithJSONDecoder(utils.JSONUnmarshal) Custom JSON decoder
…and all other fiber.Config fields Prefixed with With

cfg.URL() returns "host:port".


Controller

Groups routes under a common path prefix.

ctrl := fiberext.NewController("/api/v1").
    AddNewResource(http.MethodGet,    "/users",     listUsers).
    AddNewResource(http.MethodPost,   "/users",     createUser).
    AddNewResource(http.MethodGet,    "/users/:id", getUser).
    AddNewResource(http.MethodDelete, "/users/:id", deleteUser)

cfg.WithController(ctrl)
// → GET    /api/v1/users
// → POST   /api/v1/users
// → GET    /api/v1/users/:id
// → DELETE /api/v1/users/:id

Resource

A single route binding.

r := fiberext.NewResource(method string, path string, handler Handler) *Resource

Top-level resources are registered directly on the server:

cfg.WithResource(fiberext.NewResource(http.MethodGet, "/health", healthHandler))

Request Helpers

// Parse URL params into a struct (uses `params` field tags)
type P struct{ ID int `params:"id"` }
p, err := fiberext.FromParams[P](ctx)

// Parse JSON body into a struct
user, err := fiberext.FromBody[User](ctx)

// Parse query string into a struct (uses `query` field tags)
type Filter struct {
    Name  string `query:"name"`
    Limit int    `query:"limit"`
}
f, err := fiberext.FromQuery[Filter](ctx)

// Single URL param with optional default
id  := fiberext.GetParam(ctx, "id")
tab := fiberext.GetParam(ctx, "tab", "overview")

// Single query arg with optional default
sort := fiberext.GetQueryArg(ctx, "sort", "asc")
page := fiberext.GetQueryArg(ctx, "page", "1")

Response Helpers

All helpers accept ctx Context as the first argument. Error helpers accept optional additional arguments; success helpers with a body accept obj ...any.

2xx Success
fiberext.OK(ctx, data)                       // 200
fiberext.Created(ctx, data)                  // 201
fiberext.Accepted(ctx, data)                 // 202
fiberext.NonAuthoritativeInformation(ctx, data) // 203
fiberext.NoContent(ctx)                      // 204
fiberext.ResetContent(ctx)                   // 205
fiberext.PartialContent(ctx, data)           // 206
fiberext.MultiStatus(ctx, data)              // 207
fiberext.AlreadyReported(ctx, data)          // 208
fiberext.IMUsed(ctx, data)                   // 226
3xx Redirection
fiberext.MovedPermanently(ctx)   // 301
fiberext.Found(ctx)              // 302
fiberext.SeeOther(ctx)           // 303
fiberext.NotModified(ctx)        // 304
fiberext.TemporaryRedirect(ctx)  // 307
fiberext.PermanentRedirect(ctx)  // 308
4xx Client Errors
fiberext.BadRequest(ctx)                    // 400
fiberext.Unauthorized(ctx)                  // 401
fiberext.Forbidden(ctx)                     // 403
fiberext.NotFound(ctx)                      // 404
fiberext.MethodNotAllowed(ctx)              // 405
fiberext.Conflict(ctx)                      // 409
fiberext.Gone(ctx)                          // 410
fiberext.UnprocessableEntity(ctx)           // 422
fiberext.TooManyRequests(ctx)               // 429
fiberext.UnavailableForLegalReasons(ctx)    // 451
// … all standard 4xx codes available
5xx Server Errors
fiberext.RespondInternalError(ctx)           // 500
fiberext.NotImplemented(ctx)                 // 501
fiberext.BadGateway(ctx)                     // 502
fiberext.ServiceUnavailable(ctx)             // 503
fiberext.GatewayTimeout(ctx)                 // 504
// … all standard 5xx codes available

Types

Type Alias for
fiberext.Server *fiber.App
fiberext.Context *fiber.Ctx
fiberext.Handler fiber.Handler
fiberext.ErrorHandler fiber.ErrorHandler

Custom Error Handler

cfg.WithErrorHandler(func(c fiberext.Context, err error) error {
    code := fiber.StatusInternalServerError
    if e, ok := err.(*fiber.Error); ok {
        code = e.Code
    }
    return c.Status(code).JSON(fiber.Map{
        "code":    code,
        "message": err.Error(),
    })
})

Documentation

Overview

Package fiberext provides a thin opinionated wrapper around fiber/v2, offering builder-style configuration, typed request helpers, and HTTP status response helpers.

Index

Constants

This section is empty.

Variables

View Source
var HealthCheckResource = NewResource(fiber.MethodGet, "/health", func(ctx Context) error {
	return OK(ctx, fiber.Map{
		"status": "ok",
	})
})

Functions

func Accepted

func Accepted(ctx Context, obj ...any) error

Accepted responds with 202 Accepted and serializes obj as JSON.

func AlreadyReported

func AlreadyReported(ctx Context, obj ...any) error

AlreadyReported responds with 208 Already Reported and serializes obj as JSON.

func BadGateway

func BadGateway(ctx Context, obj ...any) error

BadGateway responds with 502 Bad Gateway.

func BadRequest

func BadRequest(ctx Context, obj ...any) error

BadRequest responds with 400 Bad Request.

func Conflict

func Conflict(ctx Context, obj ...any) error

Conflict responds with 409 Conflict.

func Continue

func Continue(ctx Context) error

Continue responds with 100 Continue.

func Created

func Created(ctx Context, obj ...any) error

Created responds with 201 Created and serializes obj as JSON.

func EarlyHints

func EarlyHints(ctx Context) error

EarlyHints responds with 103 Early Hints.

func ExpectationFailed

func ExpectationFailed(ctx Context, obj ...any) error

ExpectationFailed responds with 417 Expectation Failed.

func FailedDependency

func FailedDependency(ctx Context, obj ...any) error

FailedDependency responds with 424 Failed Dependency.

func Forbidden

func Forbidden(ctx Context, obj ...any) error

Forbidden responds with 403 Forbidden.

func Found

func Found(ctx Context) error

Found responds with 302 Found.

func FromBody

func FromBody[T any](ctx Context) (T, error)

FromBody decodes the JSON request body into T.

func FromParams

func FromParams[T any](ctx Context) (T, error)

FromParams parses URL parameters into T using the "params" struct tag.

func FromQuery

func FromQuery[T any](ctx Context) (T, error)

FromQuery parses query string parameters into T using the "query" struct tag.

func GatewayTimeout

func GatewayTimeout(ctx Context, obj ...any) error

GatewayTimeout responds with 504 Gateway Timeout.

func GetParam

func GetParam(ctx Context, key string, def ...string) string

GetParam returns the URL parameter for key, falling back to def if absent.

func GetQueryArg

func GetQueryArg(ctx Context, key string, def ...string) string

GetQueryArg returns the query argument for key, falling back to def if absent.

func Gone

func Gone(ctx Context, obj ...any) error

Gone responds with 410 Gone.

func HTTPVersionNotSupported

func HTTPVersionNotSupported(ctx Context, obj ...any) error

HTTPVersionNotSupported responds with 505 HTTP Version Not Supported.

func IMUsed

func IMUsed(ctx Context, obj ...any) error

IMUsed responds with 226 IM Used and serializes obj as JSON.

func InsufficientStorage

func InsufficientStorage(ctx Context, obj ...any) error

InsufficientStorage responds with 507 Insufficient Storage.

func LengthRequired

func LengthRequired(ctx Context, obj ...any) error

LengthRequired responds with 411 Length Required.

func Locked

func Locked(ctx Context, obj ...any) error

Locked responds with 423 Locked.

func LoopDetected

func LoopDetected(ctx Context, obj ...any) error

LoopDetected responds with 508 Loop Detected.

func MethodNotAllowed

func MethodNotAllowed(ctx Context, obj ...any) error

MethodNotAllowed responds with 405 Method Not Allowed.

func MisdirectedRequest

func MisdirectedRequest(ctx Context, obj ...any) error

MisdirectedRequest responds with 421 Misdirected Request.

func MovedPermanently

func MovedPermanently(ctx Context) error

MovedPermanently responds with 301 Moved Permanently.

func MultiStatus

func MultiStatus(ctx Context, obj ...any) error

MultiStatus responds with 207 Multi-Status and serializes obj as JSON.

func MultipleChoices

func MultipleChoices(ctx Context, obj ...any) error

MultipleChoices responds with 300 Multiple Choices and serializes obj as JSON.

func NetworkAuthenticationRequired

func NetworkAuthenticationRequired(ctx Context, obj ...any) error

NetworkAuthenticationRequired responds with 511 Network Authentication Required.

func NoContent

func NoContent(ctx Context) error

NoContent responds with 204 No Content.

func NonAuthoritativeInformation

func NonAuthoritativeInformation(ctx Context, obj ...any) error

NonAuthoritativeInformation responds with 203 and serializes obj as JSON.

func NotAcceptable

func NotAcceptable(ctx Context, obj ...any) error

NotAcceptable responds with 406 Not Acceptable.

func NotExtended

func NotExtended(ctx Context, obj ...any) error

NotExtended responds with 510 Not Extended.

func NotFound

func NotFound(ctx Context, obj ...any) error

NotFound responds with 404 Not Found.

func NotImplemented

func NotImplemented(ctx Context, obj ...any) error

NotImplemented responds with 501 Not Implemented.

func NotModified

func NotModified(ctx Context) error

NotModified responds with 304 Not Modified.

func OK

func OK(ctx Context, obj ...any) error

OK responds with 200 OK and serializes obj as JSON.

func PartialContent

func PartialContent(ctx Context, obj ...any) error

PartialContent responds with 206 Partial Content and serializes obj as JSON.

func PaymentRequired

func PaymentRequired(ctx Context, obj ...any) error

PaymentRequired responds with 402 Payment Required.

func PermanentRedirect

func PermanentRedirect(ctx Context) error

PermanentRedirect responds with 308 Permanent Redirect.

func PreconditionFailed

func PreconditionFailed(ctx Context, obj ...any) error

PreconditionFailed responds with 412 Precondition Failed.

func PreconditionRequired

func PreconditionRequired(ctx Context, obj ...any) error

PreconditionRequired responds with 428 Precondition Required.

func Processing

func Processing(ctx Context) error

Processing responds with 102 Processing.

func ProxyAuthRequired

func ProxyAuthRequired(ctx Context, obj ...any) error

ProxyAuthRequired responds with 407 Proxy Authentication Required.

func RequestEntityTooLarge

func RequestEntityTooLarge(ctx Context, obj ...any) error

RequestEntityTooLarge responds with 413 Request Entity Too Large.

func RequestHeaderFieldsTooLarge

func RequestHeaderFieldsTooLarge(ctx Context, obj ...any) error

RequestHeaderFieldsTooLarge responds with 431 Request Header Fields Too Large.

func RequestTimeout

func RequestTimeout(ctx Context, obj ...any) error

RequestTimeout responds with 408 Request Timeout.

func RequestURITooLong

func RequestURITooLong(ctx Context, obj ...any) error

RequestURITooLong responds with 414 Request-URI Too Long.

func RequestedRangeNotSatisfiable

func RequestedRangeNotSatisfiable(ctx Context, obj ...any) error

RequestedRangeNotSatisfiable responds with 416 Range Not Satisfiable.

func ResetContent

func ResetContent(ctx Context) error

ResetContent responds with 205 Reset Content.

func Respond

func Respond(ctx Context, code int, obj ...any) error

Respond writes status and optionally serializes obj as JSON.

func RespondError

func RespondError(ctx Context, code int, obj ...any) error

RespondError writes status, optionally serializes obj, and returns a fiber.Error.

func RespondInternalError

func RespondInternalError(ctx Context, obj ...any) error

RespondInternalError responds with 500 Internal Server Error.

func SeeOther

func SeeOther(ctx Context) error

SeeOther responds with 303 See Other.

func ServiceUnavailable

func ServiceUnavailable(ctx Context, obj ...any) error

ServiceUnavailable responds with 503 Service Unavailable.

func SwitchProxy

func SwitchProxy(ctx Context) error

SwitchProxy responds with 306 Switch Proxy.

func SwitchingProtocols

func SwitchingProtocols(ctx Context) error

SwitchingProtocols responds with 101 Switching Protocols.

func Teapot

func Teapot(ctx Context, obj ...any) error

Teapot responds with 418 I'm a Teapot.

func TemporaryRedirect

func TemporaryRedirect(ctx Context) error

TemporaryRedirect responds with 307 Temporary Redirect.

func TooEarly

func TooEarly(ctx Context, obj ...any) error

TooEarly responds with 425 Too Early.

func TooManyRequests

func TooManyRequests(ctx Context, obj ...any) error

TooManyRequests responds with 429 Too Many Requests.

func Unauthorized

func Unauthorized(ctx Context, obj ...any) error

Unauthorized responds with 401 Unauthorized.

func UnavailableForLegalReasons

func UnavailableForLegalReasons(ctx Context, obj ...any) error

UnavailableForLegalReasons responds with 451 Unavailable For Legal Reasons.

func UnprocessableEntity

func UnprocessableEntity(ctx Context, obj ...any) error

UnprocessableEntity responds with 422 Unprocessable Entity.

func UnsupportedMediaType

func UnsupportedMediaType(ctx Context, obj ...any) error

UnsupportedMediaType responds with 415 Unsupported Media Type.

func UpgradeRequired

func UpgradeRequired(ctx Context, obj ...any) error

UpgradeRequired responds with 426 Upgrade Required.

func UseProxy

func UseProxy(ctx Context) error

UseProxy responds with 305 Use Proxy.

func VariantAlsoNegotiates

func VariantAlsoNegotiates(ctx Context, obj ...any) error

VariantAlsoNegotiates responds with 506 Variant Also Negotiates.

Types

type Config

type Config struct {
	fiber.Config

	Host string `json:"host"`
	Port int    `json:"port"`

	TLS            bool `json:"useTls"`
	MutualTLS      bool
	CertFile       string
	KeyFile        string
	ClientCertFile string
	Certificate    *tls.Certificate
	ClientCerts    *x509.CertPool

	Controllers []*Controller
	Resources   []*Resource
	Middlewares []Handler
}

Config extends fiber.Config with server address, TLS, and routing fields.

func NewConfig

func NewConfig() *Config

NewConfig returns a zero-value Config ready for builder-style configuration.

func (*Config) URL

func (config *Config) URL() string

URL returns the server address as "host:port".

func (*Config) WithAppName

func (config *Config) WithAppName(v string) *Config

WithAppName sets the application name.

func (*Config) WithBodyLimit

func (config *Config) WithBodyLimit(v int) *Config

WithBodyLimit sets the maximum accepted request body size in bytes.

func (*Config) WithCaseSensitive

func (config *Config) WithCaseSensitive(v bool) *Config

WithCaseSensitive enables case-sensitive route matching.

func (*Config) WithCertFile

func (config *Config) WithCertFile(v string) *Config

WithCertFile sets the path to the TLS certificate file.

func (*Config) WithCertificate

func (config *Config) WithCertificate(v tls.Certificate) *Config

WithCertificate sets an in-memory TLS certificate.

func (*Config) WithClientCertFile

func (config *Config) WithClientCertFile(v string) *Config

WithClientCertFile sets the path to the client CA certificate file for mTLS.

func (*Config) WithClientCerts

func (config *Config) WithClientCerts(v *x509.CertPool) *Config

WithClientCerts sets the client CA pool for mutual TLS.

func (*Config) WithColorScheme

func (config *Config) WithColorScheme(v fiber.Colors) *Config

WithColorScheme sets a custom color scheme for startup messages.

func (*Config) WithCompressedFileSuffix

func (config *Config) WithCompressedFileSuffix(v string) *Config

WithCompressedFileSuffix sets the suffix appended to compressed static files.

func (*Config) WithConcurrency

func (config *Config) WithConcurrency(v int) *Config

WithConcurrency sets the maximum number of concurrent connections.

func (*Config) WithController

func (config *Config) WithController(controller *Controller) *Config

WithController appends controller to the list of route groups.

func (*Config) WithDisableDefaultContentType

func (config *Config) WithDisableDefaultContentType(v bool) *Config

WithDisableDefaultContentType omits the default Content-Type response header.

func (*Config) WithDisableDefaultDate

func (config *Config) WithDisableDefaultDate(v bool) *Config

WithDisableDefaultDate omits the default Date response header.

func (*Config) WithDisableHeaderNormalizing

func (config *Config) WithDisableHeaderNormalizing(v bool) *Config

WithDisableHeaderNormalizing disables automatic header name normalization.

func (*Config) WithDisableKeepalive

func (config *Config) WithDisableKeepalive(v bool) *Config

WithDisableKeepalive disables keep-alive connections.

func (*Config) WithDisablePreParseMultipartForm

func (config *Config) WithDisablePreParseMultipartForm(v bool) *Config

WithDisablePreParseMultipartForm skips automatic multipart form parsing.

func (*Config) WithDisableStartupMessage

func (config *Config) WithDisableStartupMessage(v bool) *Config

WithDisableStartupMessage suppresses the Fiber ASCII banner on start.

func (*Config) WithETag

func (config *Config) WithETag(v bool) *Config

WithETag enables ETag header generation.

func (*Config) WithEnableIPValidation

func (config *Config) WithEnableIPValidation(v bool) *Config

WithEnableIPValidation enables validation of IP addresses returned by c.IP().

func (*Config) WithEnablePrintRoutes

func (config *Config) WithEnablePrintRoutes(v bool) *Config

WithEnablePrintRoutes prints all registered routes on startup.

func (*Config) WithEnableSplittingOnParsers

func (config *Config) WithEnableSplittingOnParsers(v bool) *Config

WithEnableSplittingOnParsers splits comma-separated query/body/header values.

func (*Config) WithEnableTrustedProxyCheck

func (config *Config) WithEnableTrustedProxyCheck(v bool) *Config

WithEnableTrustedProxyCheck enables trusted proxy header validation.

func (*Config) WithErrorHandler

func (config *Config) WithErrorHandler(v ErrorHandler) *Config

WithErrorHandler sets the fiber error handler.

func (*Config) WithGETOnly

func (config *Config) WithGETOnly(v bool) *Config

WithGETOnly rejects all non-GET requests when true.

func (*Config) WithHost

func (config *Config) WithHost(v string) *Config

WithHost sets the bind host.

func (*Config) WithIdleTimeout

func (config *Config) WithIdleTimeout(v time.Duration) *Config

WithIdleTimeout sets the keep-alive idle timeout.

func (*Config) WithImmutable

func (config *Config) WithImmutable(v bool) *Config

WithImmutable makes request values immutable after the handler returns.

func (*Config) WithJSONDecoder

func (config *Config) WithJSONDecoder(v utils.JSONUnmarshal) *Config

WithJSONDecoder sets a custom JSON unmarshal function.

func (*Config) WithJSONEncoder

func (config *Config) WithJSONEncoder(v utils.JSONMarshal) *Config

WithJSONEncoder sets a custom JSON marshal function.

func (*Config) WithKeyFile

func (config *Config) WithKeyFile(v string) *Config

WithKeyFile sets the path to the TLS private key file.

func (*Config) WithMiddleware

func (config *Config) WithMiddleware(middleware Handler) *Config

WithMiddleware appends middleware to the global middleware chain.

func (*Config) WithMutualTLS

func (config *Config) WithMutualTLS(v bool) *Config

WithMutualTLS enables or disables mutual TLS (client certificate verification).

func (*Config) WithNetwork

func (config *Config) WithNetwork(v string) *Config

WithNetwork sets the network type ("tcp", "tcp4", "tcp6").

func (*Config) WithPassLocalsToViews

func (config *Config) WithPassLocalsToViews(v bool) *Config

WithPassLocalsToViews passes fiber.Ctx locals to the template engine.

func (*Config) WithPort

func (config *Config) WithPort(v int) *Config

WithPort sets the bind port.

func (*Config) WithPrefork

func (config *Config) WithPrefork(v bool) *Config

WithPrefork enables or disables multi-process prefork mode.

func (*Config) WithProxyHeader

func (config *Config) WithProxyHeader(v string) *Config

WithProxyHeader sets the header used by c.IP() when behind a proxy.

func (*Config) WithReadBufferSize

func (config *Config) WithReadBufferSize(v int) *Config

WithReadBufferSize sets the per-connection read buffer size in bytes.

func (*Config) WithReadTimeout

func (config *Config) WithReadTimeout(v time.Duration) *Config

WithReadTimeout sets the deadline for reading the full request.

func (*Config) WithReduceMemoryUsage

func (config *Config) WithReduceMemoryUsage(v bool) *Config

WithReduceMemoryUsage trades higher CPU usage for lower memory consumption.

func (*Config) WithRequestMethods

func (config *Config) WithRequestMethods(v []string) *Config

WithRequestMethods sets the list of accepted HTTP methods.

func (*Config) WithResource

func (config *Config) WithResource(resource *Resource) *Config

WithResource appends resource as a top-level route.

func (*Config) WithServerHeader

func (config *Config) WithServerHeader(v string) *Config

WithServerHeader sets the value of the Server response header.

func (*Config) WithStreamRequestBody

func (config *Config) WithStreamRequestBody(v bool) *Config

WithStreamRequestBody enables request body streaming.

func (*Config) WithStrictRouting

func (config *Config) WithStrictRouting(v bool) *Config

WithStrictRouting treats /foo and /foo/ as distinct routes when true.

func (*Config) WithTLS

func (config *Config) WithTLS(v bool) *Config

WithTLS enables or disables TLS on the listener.

func (*Config) WithTrustedProxies

func (config *Config) WithTrustedProxies(v []string) *Config

WithTrustedProxies sets the list of trusted proxy IP addresses.

func (*Config) WithUnescapePath

func (config *Config) WithUnescapePath(v bool) *Config

WithUnescapePath unescapes encoded characters in the route path.

func (*Config) WithViews

func (config *Config) WithViews(v fiber.Views) *Config

WithViews sets the template engine.

func (*Config) WithViewsLayout

func (config *Config) WithViewsLayout(v string) *Config

WithViewsLayout sets the global layout template name.

func (*Config) WithWriteBufferSize

func (config *Config) WithWriteBufferSize(v int) *Config

WithWriteBufferSize sets the per-connection write buffer size in bytes.

func (*Config) WithWriteTimeout

func (config *Config) WithWriteTimeout(v time.Duration) *Config

WithWriteTimeout sets the deadline for writing the response.

func (*Config) WithXMLEncoder

func (config *Config) WithXMLEncoder(v utils.XMLMarshal) *Config

WithXMLEncoder sets a custom XML marshal function.

type Context

type Context = *fiber.Ctx

Context is an alias for *fiber.Ctx.

type Controller

type Controller struct {
	Path      string
	Resources []*Resource
}

Controller groups Resources under a common path prefix.

func NewController

func NewController(path string) *Controller

NewController returns a Controller rooted at path.

func (*Controller) AddNewResource

func (controller *Controller) AddNewResource(method, path string, handler Handler) *Controller

AddNewResource creates a Resource from method, path and handler and appends it.

func (*Controller) AddResource

func (controller *Controller) AddResource(resource *Resource) *Controller

AddResource appends resource to the controller.

type ErrorHandler

type ErrorHandler = fiber.ErrorHandler

ErrorHandler is an alias for fiber.ErrorHandler.

type Handler

type Handler = fiber.Handler

Handler is an alias for fiber.Handler.

type Resource

type Resource struct {
	Method  string
	Path    string
	Handler Handler

	Static       bool
	WebPath      string
	FilePath     string
	StaticConfig fiber.Static
}

Resource is a single route binding.

func NewResource

func NewResource(method, path string, handler Handler) *Resource

NewResource returns a Resource for the given HTTP method, path and handler.

type Server

type Server = *fiber.App

Server is an alias for *fiber.App.

func Run

func Run(ctx context.Context, config *Config) Server

Run builds a fiber server from cfg, registers middlewares, resources and controllers, then starts listening in a background goroutine. Cancelling ctx triggers graceful shutdown. Returns the underlying *fiber.App.

Jump to

Keyboard shortcuts

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