fiber

package module
v2.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0, BSD-3-Clause Imports: 24 Imported by: 2

README

Fiber v2 instrumentation

Use Wrap to trace a *fiber.App and enable AppSec checks when AppSec is active. Orchestrion calls Wrap automatically.

import (
    fibertrace "github.com/DataDog/dd-trace-go/contrib/gofiber/fiber.v2/v2"
    "github.com/gofiber/fiber/v2"
    fiberrecover "github.com/gofiber/fiber/v2/middleware/recover"
)

func newApp() *fiber.App {
    app := fibertrace.Wrap(fiber.New())
    // Register panic recovery immediately after Wrap.
    app.Use(fiberrecover.New())
    app.Get("/users/:id", func(c *fiber.Ctx) error {
        return c.SendString(c.Params("id"))
    })
    return app
}

Set up the app with Wrap

Call Wrap(app, opts...) before you register middleware, routes, or mounted apps. Wrap installs route guards during setup. Fiber's matcher gives the path parameters to these guards before they call the user handlers. Thus, a block on a path parameter prevents those handlers from running.

Important behavior:

  • Wrap each mounted app. If a child app does not have its own Wrap call, its parameters are checked only after its handlers return. Then a block cannot prevent the side effects of those handlers.
  • Mounted apps use the request span and options of the first wrapped app. This includes WithIgnoreRequest: if the first app ignores a request, mounted apps also skip tracing and AppSec.
  • Consecutive route registrations can share a handler chain. Every appended handler is guarded.
  • Repeated Wrap calls apply options, but do not add another middleware.
  • Calls to Wrap on the same app must not run concurrently. All route registration must finish before the app serves requests.
  • A block in a parameterized group middleware reports the route of that group, because the request has not reached the endpoint yet.
  • Parsed bodies still require an explicit appsec.MonitorParsedHTTPBody(c.UserContext(), body) call. There is no automatic BodyParser hook.
The older Middleware API

Use Wrap instead of app.Use(fibertrace.Middleware()). Do not install both. The global Middleware form stays compatible, but it can only report endpoint parameters after the handler chain. It cannot prevent the side effects of those handlers.

Request monitoring

The middleware starts the WAF operation before the handler chain. It keeps the raw request target for WAF inspection. The WAF inspects all the query and cookie pairs that fasthttp parses, including repeated keys. Fiber reads its values (for example, with c.Query and c.Cookies) from these pairs. Invalid escapes, semicolons, and cookie values that net/http rejects do not disable monitoring, and do not remove values that the application can read.

Errors

With AppSec enabled:

  • The middleware renders returned errors through the error handler of the Fiber app, before it reports the response to the WAF. The error handler runs one time, only when necessary. Fiber selects the error handler as it does without tracing: a mounted app that sets its own ErrorHandler renders its errors.
  • The original error is recorded on the span. If AppSec blocks the response, the block is recorded instead.
  • A pending block has priority over the error handler. It replaces the body and headers that the error handler sets.
  • Earlier middleware receives nil from c.Next() for these handled errors. Put error logging or counting in the configured error handler.

Timeouts set after tracing returns hide a block. If code calls TimeoutError* on the fasthttp context after AppSec delivers a block (for example, middleware registered before tracing calls it after c.Next()), fasthttp sends the timeout response, not the block. The span and the AppSec telemetry still report the block as applied. fasthttp cannot clear a timeout response.

With AppSec disabled, error propagation does not change. Fiber renders returned errors after tracing returns. Thus, the span status can show the response before the error, not the final status sent to the client.

Panic recovery

Register panic-recovery middleware immediately after Wrap (or immediately after Middleware if you use the older API), before other middleware and routes. Recovery then runs inside the monitored handler chain, and the error handler renders the response before the WAF inspects it.

Recovery registered before tracing is not supported for AppSec panic handling. It runs too late: AppSec cannot inspect its final response, or prevent it from replacing a pending block.

Tracing does not install or replace recovery. Panics that are not recovered still propagate. For such a panic, AppSec still reports the response to the WAF. If a response rule blocks, the span reports the block as applied, but the client receives no response. Custom recovery callbacks stay under the control of the application.

Testing

From the contrib/gofiber/fiber.v2 directory, run the tests and the benchmark:

go test ./...
go test -run '^$' -bench BenchmarkFiberMiddleware ./...

The tests cover parsing, error responses, blocking, and connection reuse. BenchmarkFiberMiddleware measures requests with AppSec off and on. The Orchestrion Fiber case in internal/orchestrion/_integration/fiber.v2 verifies blocking without manual middleware.

Documentation

Overview

Package fiber provides tracing functions for tracing the fiber package (https://github.com/gofiber/fiber).

Example
package main

import (
	fibertrace "github.com/DataDog/dd-trace-go/contrib/gofiber/fiber.v2/v2"

	"github.com/DataDog/dd-trace-go/v2/ddtrace/tracer"

	"github.com/gofiber/fiber/v2"
	fiberrecover "github.com/gofiber/fiber/v2/middleware/recover"
)

func main() {
	// Start the tracer
	tracer.Start()
	defer tracer.Stop()

	// Create a fiber v2 Router
	router := fiber.New()

	// Install tracing and AppSec route guards before registering endpoints.
	fibertrace.Wrap(router)

	// Recovery must run inside tracing so AppSec sees the rendered error.
	router.Use(fiberrecover.New())

	// Set up some endpoints.
	router.Get("/", func(c *fiber.Ctx) error {
		return c.SendString("test")
	})

	// And start gathering request traces
	router.Listen(":8080")
}
Example (WithServiceName)
package main

import (
	fibertrace "github.com/DataDog/dd-trace-go/contrib/gofiber/fiber.v2/v2"

	"github.com/DataDog/dd-trace-go/v2/ddtrace/tracer"

	"github.com/gofiber/fiber/v2"
)

func main() {
	// Start the tracer
	tracer.Start()
	defer tracer.Stop()

	// Create a fiber v2 Router
	router := fiber.New()

	// Install tracing and AppSec route guards with your desired service name.
	fibertrace.Wrap(router, fibertrace.WithService("fiber"))

	// Set up some endpoints.
	router.Get("/", func(c *fiber.Ctx) error {
		return c.SendString("test")
	})

	// And start gathering request traces
	router.Listen(":8080")
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Middleware

func Middleware(opts ...Option) func(c *fiber.Ctx) error

Middleware returns middleware that will trace incoming requests. With AppSec enabled, pending blocks take priority over the error handler. Other returned errors are rendered through the application's error handler before the WAF inspects the response. Handled errors are not returned to earlier middleware. The original error is recorded on the span unless the response is blocked; then the block is reported instead.

Register panic-recovery middleware immediately after this middleware, before other middleware and routes, so it runs inside the monitored handler chain. Recovery outside it happens too late for AppSec to inspect the rendered error response or preserve a pending block. This middleware does not recover panics itself.

Use Wrap for whole-app instrumentation. A global Middleware runs before Fiber matches the endpoint and can only check its path parameters afterward; it cannot prevent handler side effects from a path-parameter attack.

func Wrap added in v2.12.0

func Wrap(app *fiber.App, opts ...Option) *fiber.App

Wrap installs tracing and AppSec route guards and returns app. Call it before registering middleware, routes, or mounted apps, and before serving requests. Wrap each mounted app as well. The first wrapped app reached by a request owns its span and options; mounted apps do not add another span. If its WithIgnoreRequest option skips a request, mounted apps also skip monitoring.

Register panic-recovery middleware immediately after Wrap, before other middleware and routes. AppSec can then inspect the rendered error response and preserve pending blocks. Wrap does not install recovery itself; without it, handler panics still propagate.

Route guards inspect Fiber's matched path parameters before calling that route's user handlers. Global Middleware alone cannot provide this protection.

Repeated calls apply additional options without installing duplicate handlers. This lets explicit options override Orchestrion's automatic setup. All calls must happen during setup, not while the app serves requests. Calls on the same app must not run concurrently. Complete route registration before serving. Wrap panics if the first call occurs after middleware, routes, or mounts have been registered. Under Orchestrion, the first call happens at fiber.New.

Types

type Option

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

Option describes options for the Fiber.v2 integration.

type OptionFn

type OptionFn func(*config)

OptionFn represents options applicable to Middleware and Wrap.

func WithAnalytics

func WithAnalytics(on bool) OptionFn

WithAnalytics enables Trace Analytics for all started spans.

func WithAnalyticsRate

func WithAnalyticsRate(rate float64) OptionFn

WithAnalyticsRate sets the sampling rate for Trace Analytics events correlated to started spans.

func WithIgnoreRequest

func WithIgnoreRequest(fn func(*fiber.Ctx) bool) OptionFn

WithIgnoreRequest specifies a function which will be used to determining if the incoming HTTP request tracing should be skipped.

func WithResourceNamer

func WithResourceNamer(fn func(*fiber.Ctx) string) OptionFn

WithResourceNamer specifies a function which will be used to obtain the resource name for a given request taking the go-fiber context as input

func WithService

func WithService(name string) OptionFn

WithService sets the given service name for the router.

func WithSpanOptions

func WithSpanOptions(opts ...tracer.StartSpanOption) OptionFn

WithSpanOptions applies the given set of options to the spans started by the router.

func WithStatusCheck

func WithStatusCheck(fn func(statusCode int) bool) OptionFn

WithStatusCheck allow setting of a function to tell whether a status code is an error

Jump to

Keyboard shortcuts

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