Skip to main content

Overview

The sentry middleware integrates with Sentry for error tracking, performance monitoring, and debugging. Use it when you need:
  • Error tracking
  • Performance monitoring
  • Issue management

Installation

import "github.com/go-mizu/mizu/middlewares/sentry"

Quick Start

app := mizu.New()

// Initialize Sentry
sentry.Init(sentry.Options{
    DSN: "https://[email protected]/project",
})

app.Use(sentry.Middleware())

Configuration

Options

OptionTypeDefaultDescription
DSNstringRequiredSentry DSN
Environmentstring""Environment name
Releasestring""Release version
SampleRatefloat641.0Error sample rate
TracesSampleRatefloat640Performance sample rate

Examples

Basic Setup

sentry.Init(sentry.Options{
    DSN: os.Getenv("SENTRY_DSN"),
})

app.Use(sentry.Middleware())

With Environment

sentry.Init(sentry.Options{
    DSN:         os.Getenv("SENTRY_DSN"),
    Environment: os.Getenv("ENV"),
    Release:     "v1.0.0",
})

Performance Monitoring

sentry.Init(sentry.Options{
    DSN:              os.Getenv("SENTRY_DSN"),
    TracesSampleRate: 0.1, // 10% of transactions
})

Manual Error Capture

app.Get("/", func(c *mizu.Ctx) error {
    if err := doSomething(); err != nil {
        sentry.CaptureError(c, err)
        return c.JSON(500, map[string]string{"error": "Internal error"})
    }
    return c.JSON(200, data)
})

Add Context

app.Use(func(next mizu.Handler) mizu.Handler {
    return func(c *mizu.Ctx) error {
        sentry.SetUser(c, sentry.User{
            ID:    getUserID(c),
            Email: getEmail(c),
        })
        sentry.SetTag(c, "feature", "checkout")
        return next(c)
    }
})

API Reference

Functions

// Init initializes Sentry
func Init(opts Options) error

// Middleware creates Sentry middleware
func Middleware() mizu.Middleware

// CaptureError sends error to Sentry
func CaptureError(c *mizu.Ctx, err error)

// SetUser sets user context
func SetUser(c *mizu.Ctx, user User)

// SetTag sets a tag
func SetTag(c *mizu.Ctx, key, value string)

Technical Details

Architecture

The Sentry middleware is built around a lightweight error tracking system with the following components: Hub: Central management structure that handles event capture, storage, and transport. Each middleware instance creates a Hub that is stored in the request context. Event: Represents an error event with metadata including:
  • Event ID, timestamp, and severity level
  • Exception details with stack traces
  • HTTP request information (URL, method, headers, query strings)
  • User context, tags, and extra data
  • Runtime context (Go version, platform)
Transport: Interface for sending events to Sentry. Supports custom implementations via the Transport interface:
  • MockTransport: For testing, stores events in memory
  • HTTPTransport: Sends events to Sentry via HTTP
  • Custom transports can be implemented by satisfying the Transport interface

Event Capture Flow

  1. Middleware wraps the handler with panic recovery
  2. Hub is stored in request context for the lifetime of the request
  3. Errors returned from handlers are automatically captured
  4. Panics are caught, converted to events, and re-thrown
  5. Events are processed through hooks (BeforeSend) before sending
  6. Events are sent asynchronously via the configured transport

Stack Trace Capture

Stack traces are captured using Go’s runtime.Callers and runtime.CallersFrames:
  • Frames include filename, function name, line number, and absolute path
  • Configurable skip depth to exclude middleware internals
  • Frames are reversed to show most recent call first

Header Filtering

Sensitive headers are automatically filtered from request data:
  • Authorization
  • Cookie
  • X-Api-Key

Sampling

Events can be sampled based on SampleRate (0.0 to 1.0):
  • 1.0 captures all events (default)
  • 0.5 captures 50% of events
  • Sampling uses nanosecond precision for distribution

Context Management

The middleware uses Go’s context to store:
  • Hub instance (via hubKey)
  • User information (via userContextKey)
  • Tags (via tagsContextKey)
  • Extra data (via extraContextKey)

Best Practices

  • Use environment for staging/production
  • Set release for version tracking
  • Add user context for debugging
  • Sample transactions in production

Testing

The Sentry middleware includes comprehensive test coverage for all major features:
Test CaseDescriptionExpected Behavior
TestNewBasic middleware initializationMiddleware processes requests successfully
TestCaptureErrorError capture from handlerError event captured with correct message and level “error”
TestCaptureMessageManual message captureMessage event captured with level “info”
TestCapturePanicPanic recoveryPanic captured as “fatal” level event and re-thrown
TestEnvironmentAndReleaseEnvironment and release configurationEvents include configured environment and release values
TestTagsDefault tags configurationDefault tags applied to all events
TestBeforeSendBeforeSend hook modificationHook can modify events before sending
TestBeforeSendDropBeforeSend hook event droppingReturning nil from hook prevents event capture
TestRequestInfoHTTP request metadata captureEvent includes method, URL, query string, and headers
TestSensitiveHeadersFilteredSensitive header filteringAuthorization, Cookie, and X-Api-Key headers excluded
TestStacktraceStack trace generationEvents include stack trace with frames
TestMockTransportMock transport for testingEvents sent to custom transport
TestHubEventsHub event storage and clearingEvents can be retrieved and cleared from hub
TestGetHubHub retrieval from contextHub accessible within request handlers
TestSetUserUser context settingUser information can be set on context
TestSetTagAndExtraDynamic tags and extra dataTags and extra data can be set per request