sentryhttp

package
v0.28.0 Latest Latest
Warning

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

Go to latest
Published: May 27, 2024 License: MIT Imports: 5 Imported by: 161

README


Official Sentry net/http Handler for Sentry-go SDK

go.dev: https://pkg.go.dev/github.com/getsentry/sentry-go/http

Example: https://github.com/getsentry/sentry-go/tree/master/_examples/http

Installation

go get github.com/getsentry/sentry-go/http
import (
    "fmt"
    "net/http"

    "github.com/getsentry/sentry-go"
    sentryhttp "github.com/getsentry/sentry-go/http"
)

// To initialize Sentry's handler, you need to initialize Sentry itself beforehand
if err := sentry.Init(sentry.ClientOptions{
    Dsn: "your-public-dsn",
}); err != nil {
    fmt.Printf("Sentry initialization failed: %v\n", err)
}

// Create an instance of sentryhttp
sentryHandler := sentryhttp.New(sentryhttp.Options{})

// Once it's done, you can setup routes and attach the handler as one of your middleware
http.Handle("/", sentryHandler.Handle(&handler{}))
http.HandleFunc("/foo", sentryHandler.HandleFunc(func(rw http.ResponseWriter, r *http.Request) {
    panic("y tho")
}))

fmt.Println("Listening and serving HTTP on :3000")

// And run it
if err := http.ListenAndServe(":3000", nil); err != nil {
    panic(err)
}

Configuration

sentryhttp accepts a struct of Options that allows you to configure how the handler will behave.

Currently it respects 3 options:

// Whether Sentry should repanic after recovery, in most cases it should be set to true,
// and you should gracefully handle http responses.
Repanic         bool
// Whether you want to block the request before moving forward with the response.
// Useful, when you want to restart the process after it panics.
WaitForDelivery bool
// Timeout for the event delivery requests.
Timeout         time.Duration

Usage

sentryhttp attaches an instance of *sentry.Hub (https://pkg.go.dev/github.com/getsentry/sentry-go#Hub) to the request's context, which makes it available throughout the rest of the request's lifetime. You can access it by using the sentry.GetHubFromContext() method on the request itself in any of your proceeding middleware and routes. And it should be used instead of the global sentry.CaptureMessage, sentry.CaptureException, or any other calls, as it keeps the separation of data between the requests.

Keep in mind that *sentry.Hub won't be available in middleware attached before to sentryhttp!

type handler struct{}

func (h *handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	if hub := sentry.GetHubFromContext(r.Context()); hub != nil {
		hub.WithScope(func(scope *sentry.Scope) {
			scope.SetExtra("unwantedQuery", "someQueryDataMaybe")
			hub.CaptureMessage("User provided unwanted query string, but we recovered just fine")
		})
	}
	rw.WriteHeader(http.StatusOK)
}

func enhanceSentryEvent(handler http.HandlerFunc) http.HandlerFunc {
	return func(rw http.ResponseWriter, r *http.Request) {
		if hub := sentry.GetHubFromContext(r.Context()); hub != nil {
			hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt")
		}
		handler(rw, r)
	}
}

// Later in the code

sentryHandler := sentryhttp.New(sentryhttp.Options{
    Repanic: true,
})

http.Handle("/", sentryHandler.Handle(&handler{}))
http.HandleFunc("/foo", sentryHandler.HandleFunc(
    enhanceSentryEvent(func(rw http.ResponseWriter, r *http.Request) {
        panic("y tho")
    }),
))

fmt.Println("Listening and serving HTTP on :3000")

if err := http.ListenAndServe(":3000", nil); err != nil {
    panic(err)
}
Accessing Request in BeforeSend callback
sentry.Init(sentry.ClientOptions{
    Dsn: "your-public-dsn",
    BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
        if hint.Context != nil {
            if req, ok := hint.Context.Value(sentry.RequestContextKey).(*http.Request); ok {
                // You have access to the original Request here
            }
        }

        return event
    },
})

Documentation

Overview

Package sentryhttp provides Sentry integration for servers based on the net/http package.

Example

For a longer and executable example, see https://github.com/getsentry/sentry-go/tree/master/_examples/http.

// Initialize the Sentry SDK once in the main function.
// sentry.Init(...)

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
	// Use GetHubFromContext to get a hub associated with the current
	// request. Hubs provide data isolation, such that tags, breadcrumbs
	// and other attributes are never mixed up across requests.
	hub := sentry.GetHubFromContext(r.Context())
	_, err := http.Get("example.com")
	if err != nil {
		hub.CaptureException(err)
	}
})

// Wrap the default mux with Sentry to capture panics and report errors.
//
// Alternatively, you can also wrap individual handlers if you need to use
// different options for different parts of your app.
handler := sentryhttp.New(sentryhttp.Options{}).Handle(http.DefaultServeMux)

server := http.Server{
	Addr:              ":0",
	ReadHeaderTimeout: 3 * time.Second,
	Handler:           handler,
}
server.ListenAndServe()
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

A Handler is an HTTP middleware factory that provides integration with Sentry.

func New

func New(options Options) *Handler

New returns a new Handler. Use the Handle and HandleFunc methods to wrap existing HTTP handlers.

func (*Handler) Handle

func (h *Handler) Handle(handler http.Handler) http.Handler

Handle works as a middleware that wraps an existing http.Handler. A wrapped handler will recover from and report panics to Sentry, and provide access to a request-specific hub to report messages and errors.

func (*Handler) HandleFunc

func (h *Handler) HandleFunc(handler http.HandlerFunc) http.HandlerFunc

HandleFunc is like Handle, but with a handler function parameter for cases where that is convenient. In particular, use it to wrap a handler function literal.

http.Handle(pattern, h.HandleFunc(func (w http.ResponseWriter, r *http.Request) {
    // handler code here
}))

type Options

type Options struct {
	// Repanic configures whether to panic again after recovering from a panic.
	// Use this option if you have other panic handlers or want the default
	// behavior from Go's http package, as documented in
	// https://golang.org/pkg/net/http/#Handler.
	Repanic bool
	// WaitForDelivery indicates, in case of a panic, whether to block the
	// current goroutine and wait until the panic event has been reported to
	// Sentry before repanicking or resuming normal execution.
	//
	// This option is normally not needed. Unless you need different behaviors
	// for different HTTP handlers, configure the SDK to use the
	// HTTPSyncTransport instead.
	//
	// Waiting (or using HTTPSyncTransport) is useful when the web server runs
	// in an environment that interrupts execution at the end of a request flow,
	// like modern serverless platforms.
	WaitForDelivery bool
	// Timeout for the delivery of panic events. Defaults to 2s. Only relevant
	// when WaitForDelivery is true.
	//
	// If the timeout is reached, the current goroutine is no longer blocked
	// waiting, but the delivery is not canceled.
	Timeout time.Duration
}

Options configure a Handler.

Jump to

Keyboard shortcuts

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