Documentation
¶
Index ¶
- Constants
- func AdminAuthMiddleware(password string) fiber.Handler
- func CorsHandler(cfg *cors.Config) fiber.Handler
- func DefaultHandler[T any, P Params[T]](key ...string) fiber.Handler
- func ErrorHandler(maskMessage string, onError func(traceId string, err *ErrorResponse)) func(*fiber.Ctx, error) error
- func GetFromContext[T any](ctx *fiber.Ctx, keyStr string) (*T, error)
- func HandlerInitInCtx[T any](keyStr string) fiber.Handler
- func MetricsHandler(cfg *monitor.Config) fiber.Handler
- func ParseRequest(ctx *fiber.Ctx, params interface{}) error
- func PprofHandler(prefix string) fiber.Handler
- func RecoverHandler() fiber.Handler
- func RequestLogMiddleware(fn func(path, traceId string)) fiber.Handler
- func RequestTimeoutMiddleware(d time.Duration) fiber.Handler
- func TraceIdMiddleware() fiber.Handler
- type Config
- type Endpoint
- type ErrorResponse
- type FiberApp
- type FiberEndpoint
- func DELETE(path string, handlers ...fiber.Handler) FiberEndpoint
- func GET(path string, handlers ...fiber.Handler) FiberEndpoint
- func HEAD(path string, handlers ...fiber.Handler) FiberEndpoint
- func NewEndpoint(method, path string, handlers ...fiber.Handler) FiberEndpoint
- func OPTIONS(path string, handlers ...fiber.Handler) FiberEndpoint
- func PATCH(path string, handlers ...fiber.Handler) FiberEndpoint
- func POST(path string, handlers ...fiber.Handler) FiberEndpoint
- func PUT(path string, handlers ...fiber.Handler) FiberEndpoint
- type Params
- type SwaggerConfig
Constants ¶
const TraceIdKey = "X-Trace-Id"
Variables ¶
This section is empty.
Functions ¶
func AdminAuthMiddleware ¶
AdminAuthMiddleware checks the X-Admin-Password request header. If password is empty, all requests are denied. Uses constant-time comparison to prevent timing attacks.
func CorsHandler ¶
CorsHandler returns a CORS middleware. Passing nil uses the fiber default policy.
func DefaultHandler ¶
DefaultHandler parses the request into a P, validates it, and stores the result in ctx.Locals under the given key (default: "params"). Use GetFromContext to retrieve it in downstream handlers.
func ErrorHandler ¶
func ErrorHandler( maskMessage string, onError func(traceId string, err *ErrorResponse), ) func(*fiber.Ctx, error) error
ErrorHandler returns a fiber error handler that serialises errors as ErrorResponse JSON.
maskMessage, when non-empty, replaces raw internal server error messages. The original message is still shown when the ?debug= query param is present.
onError is an optional callback invoked for every error response — use it to integrate rocklog or any other logger without coupling rockfiber to a specific library.
func GetFromContext ¶
GetFromContext retrieves a *T stored under keyStr in ctx.Locals. Returns an error if the key is missing or the stored value has the wrong type.
func HandlerInitInCtx ¶
HandlerInitInCtx returns a middleware that initialises a zero-value *T in ctx.Locals under keyStr. Useful for passing objects between middleware layers.
func MetricsHandler ¶
MetricsHandler returns a monitor middleware. Passing nil uses a sensible default.
func ParseRequest ¶
ParseRequest populates params from the incoming request.
Supported struct tags:
reqHeader:"name" — request header query:"name" — query parameter params:"name" — URL path parameter json/xml/form — request body (non-GET only) form:"name" — multipart file (*multipart.FileHeader or []*multipart.FileHeader)
Parsing order: query → body → headers → path params. Path params are applied last and will overwrite earlier values for the same field.
func PprofHandler ¶
PprofHandler registers pprof routes under the given path prefix.
func RecoverHandler ¶
RecoverHandler recovers from panics and writes the stack trace to stderr.
func RequestLogMiddleware ¶
RequestLogMiddleware calls fn with the request URI and trace ID before each handler. Use the OnRequest hook in Config instead of wiring this manually.
func RequestTimeoutMiddleware ¶
RequestTimeoutMiddleware sets a context deadline on every request. Any context-aware operation (DB queries, HTTP calls, etc.) will respect this deadline. d must be greater than zero; use Config.RequestTimeout instead of wiring this manually.
func TraceIdMiddleware ¶
TraceIdMiddleware generates a new X-Trace-Id UUID for each request, or propagates an existing one if already present in the incoming request headers. Incoming values are sanitised: values longer than 64 chars or containing control characters (e.g. newlines) are rejected and a fresh UUID is generated instead.
Types ¶
type Config ¶
type Config struct {
// Must be set in code — contains functions and types unsupported by rockconfig.
App fiber.Config `config:"-"`
Port string // required
EndpointsPathPrefix string `config:",omitempty"` // e.g. "/api/v1"
AdminEndpointsPath string `config:",omitempty"` // defaults to "/admin"
AdminPassword string `config:",omitempty"` // X-Admin-Password header; empty = deny all
ShutdownTimeout time.Duration `config:",omitempty"` // defaults to 30s
// TLS — both must be set together to enable HTTPS.
TLSCertFile string `config:",omitempty"`
TLSKeyFile string `config:",omitempty"`
// Global middlewares (all routes including /status and admin).
Compress bool `config:",omitempty"` // gzip/deflate/brotli compression
Helmet bool `config:",omitempty"` // security headers: X-Frame-Options, CSP, HSTS, etc.
// Endpoint middlewares (routes under EndpointsPathPrefix only).
UseTraceId bool `config:",omitempty"`
RequestTimeout time.Duration `config:",omitempty"` // context deadline; 0 = disabled
// Must be set in code — complex third-party config types.
RateLimit *limiter.Config `config:"-"` // nil = disabled
Swagger *SwaggerConfig `config:"-"` // nil = disabled
MonitoringConfig *monitor.Config `config:"-"` // nil = default
CorsConfig *cors.Config `config:"-"` // nil = allow all origins
// MaskInternalServerErrorMessage replaces raw 500 messages in responses.
// The real message is still visible via ?debug= query param.
MaskInternalServerErrorMessage string `config:",omitempty"`
// Must be set in code — function types.
NotFound fiber.Handler `config:"-"` // catch-all for unmatched routes
OnRequest func(path, traceId string) `config:"-"` // called at the start of every request
OnError func(traceId string, err *ErrorResponse) `config:"-"` // called on error responses
}
Config holds all configuration for a FiberApp.
Compatible with rockconfig.InitFromFile — fields marked config:"-" cannot be loaded from a file and must be set in code. All other fields are optional (omitempty) except Port which is required.
Example config.yaml:
port: "8080" endpoints_path_prefix: "/api/v1" admin_password: "secret" use_trace_id: true compress: true helmet: true request_timeout: "5s" mask_internal_server_error_message: "internal server error"
type Endpoint ¶
type Endpoint[HandlerFunc any] interface { GetPath() string GetMethod() string GetHandlers() []HandlerFunc }
Endpoint is a generic route descriptor.
type ErrorResponse ¶
type ErrorResponse struct {
Code int `json:"code"`
Status string `json:"status"`
Message string `json:"message"`
Source string `json:"source,omitempty"`
Action string `json:"action,omitempty"`
}
ErrorResponse is the standard error payload returned by all API error responses. It implements the error interface, so it can be returned directly from fiber handlers.
func NewError ¶
func NewError(statusCode int, message string) *ErrorResponse
NewError creates an ErrorResponse with the given HTTP status code and message.
func (*ErrorResponse) Error ¶
func (e *ErrorResponse) Error() string
func (*ErrorResponse) WithAction ¶
func (e *ErrorResponse) WithAction(action string) *ErrorResponse
WithAction sets the Action field and returns the receiver for chaining.
func (*ErrorResponse) WithSource ¶
func (e *ErrorResponse) WithSource(source string) *ErrorResponse
WithSource sets the Source field and returns the receiver for chaining.
type FiberApp ¶
type FiberApp struct {
// contains filtered or unexported fields
}
FiberApp is a fiber-based HTTP server that satisfies the rockengine App interface:
Init(ctx context.Context) error Exec(ctx context.Context) error Stop() []error
func New ¶
New creates a FiberApp with the given config and endpoints. Pass endpoints via NewEndpoint, GET, POST, etc.
func (*FiberApp) Exec ¶
Exec registers endpoints and starts the HTTP server. Blocks until ctx is cancelled or the server exits with an error.
func (*FiberApp) SetEndpoints ¶
func (a *FiberApp) SetEndpoints(endpoints []FiberEndpoint)
type FiberEndpoint ¶
FiberEndpoint is an Endpoint for fiber handlers.
func NewEndpoint ¶
func NewEndpoint(method, path string, handlers ...fiber.Handler) FiberEndpoint
NewEndpoint creates a FiberEndpoint with the given method, path and handlers.
type SwaggerConfig ¶
type SwaggerConfig struct {
Path string
Config swagger.Config
OAuth *swagger.OAuthConfig
Filter swagger.FilterConfig
SyntaxHighlight *swagger.SyntaxHighlightConfig
}
SwaggerConfig configures the Swagger UI endpoint.