Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fiber integration #795

Merged
merged 19 commits into from
Mar 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- Accept `interface{}` for span data values ([#784](https://github.com/getsentry/sentry-go/pull/784))
- Automatic transactions for Echo integration ([#722](https://github.com/getsentry/sentry-go/pull/722))
- Automatic transactions for Fasthttp integration ([#732](https://github.com/getsentry/sentry-go/pull/723))
- Add `Fiber` integration ([#795](https://github.com/getsentry/sentry-go/pull/795))

## 0.27.0

Expand Down
63 changes: 63 additions & 0 deletions _examples/fiber/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package main

import (
"fmt"

"github.com/getsentry/sentry-go"
sentryfiber "github.com/getsentry/sentry-go/fiber"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/utils"
)

func main() {
_ = sentry.Init(sentry.ClientOptions{
Dsn: "",
BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
if hint.Context != nil {
if ctx, ok := hint.Context.Value(sentry.RequestContextKey).(*fiber.Ctx); ok {
// You have access to the original Context if it panicked
fmt.Println(utils.CopyString(ctx.Hostname()))
}
}
fmt.Println(event)
return event
},
Debug: true,
AttachStacktrace: true,
})

// Later in the code
sentryHandler := sentryfiber.New(sentryfiber.Options{
Repanic: true,
WaitForDelivery: true,
})

enhanceSentryEvent := func(ctx *fiber.Ctx) error {
if hub := sentryfiber.GetHubFromContext(ctx); hub != nil {
hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt")
}
return ctx.Next()
}

app := fiber.New()

app.Use(sentryHandler)

app.All("/foo", enhanceSentryEvent, func(c *fiber.Ctx) error {
panic("y tho")
})

app.All("/", func(ctx *fiber.Ctx) error {
if hub := sentryfiber.GetHubFromContext(ctx); hub != nil {
hub.WithScope(func(scope *sentry.Scope) {
scope.SetExtra("unwantedQuery", "someQueryDataMaybe")
hub.CaptureMessage("User provided unwanted query string, but we recovered just fine")
})
}
return ctx.SendStatus(fiber.StatusOK)
})

if err := app.Listen(":3000"); err != nil {
panic(err)
}
}
127 changes: 127 additions & 0 deletions fiber/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
<p align="center">
<a href="https://sentry.io" target="_blank" align="center">
<img src="https://sentry-brand.storage.googleapis.com/sentry-logo-black.png" width="280">
</a>
<br />
</p>

# Official Sentry fiber Handler for Sentry-go SDK

**Godoc:** https://godoc.org/github.com/getsentry/sentry-go/fiber
vaind marked this conversation as resolved.
Show resolved Hide resolved

**Example:** https://github.com/getsentry/sentry-go/tree/master/example/fiber

## Installation

```sh
go get github.com/getsentry/sentry-go/fiber
```

```go
import (
"fmt"
"github.com/gofiber/fiber/v2"
"github.com/getsentry/sentry-go"
sentryfiber "github.com/getsentry/sentry-go/fiber"
"github.com/gofiber/fiber/v2/utils"
)
```

To initialize Sentry's handler, you need to initialize Sentry itself beforehand

```go
if err := sentry.Init(sentry.ClientOptions{
Dsn: "your-public-dsn",
}); err != nil {
fmt.Printf("Sentry initialization failed: %v\n", err)
}

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

// Once it's done, you can attach the handler as one of your middlewares
app := fiber.New()

app.Use(sentryHandler)

// And run it
app.Listen(":3000")
```

## Configuration

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

Currently it respects 3 options:

```go
// Repanic configures whether Sentry should repanic after recovery, in most cases it should be set to false,
// as fasthttp doesn't include it's own Recovery handler.
Repanic bool
// WaitForDelivery configures whether you want to block the request before moving forward with the response.
// Because fasthttp doesn't include it's own `Recovery` handler, it will restart the application,
// and event won't be delivered otherwise.
WaitForDelivery bool
// Timeout for the event delivery requests.
Timeout time.Duration
```

## Usage

`sentryfiber` attaches an instance of `*sentry.Hub` (https://godoc.org/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 `sentryfiber.GetHubFromContext()` method on the context 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 `sentryfiber`!**

```go
// Later in the code
sentryHandler := sentryfiber.New(sentryfiber.Options{
Repanic: true,
WaitForDelivery: true,
})

enhanceSentryEvent := func(ctx *fiber.Ctx) {
if hub := sentryfiber.GetHubFromContext(ctx); hub != nil {
hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt")
}
ctx.Next()
}

app := fiber.New()

app.Use(sentryHandler)

app.All("/foo", enhanceSentryEvent, func(ctx *fiber.Ctx) {
panic("y tho")
})

app.All("/", func(ctx *fiber.Ctx) {
if hub := sentryfiber.GetHubFromContext(ctx); hub != nil {
hub.WithScope(func(scope *sentry.Scope) {
scope.SetExtra("unwantedQuery", "someQueryDataMaybe")
hub.CaptureMessage("User provided unwanted query string, but we recovered just fine")
})
}
ctx.Status(fiber.StatusOK)
})

app.Listen(":3000")
```

### Accessing Context in `BeforeSend` callback

```go
sentry.Init(sentry.ClientOptions{
Dsn: "your-public-dsn",
BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
if hint.Context != nil {
if ctx, ok := hint.Context.Value(sentry.RequestContextKey).(*fiber.Ctx); ok {
// You have access to the original Context if it panicked
fmt.Println(ctx.Hostname())
}
}
return event
},
})
```
115 changes: 115 additions & 0 deletions fiber/sentryfiber.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package sentryfiber

import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/url"
"time"

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

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

const valuesKey = "sentry"

type handler struct {
repanic bool
waitForDelivery bool
timeout time.Duration
}

type Options struct {
// Repanic configures whether Sentry should repanic after recovery, in most cases it should be set to false,
// as fasthttp doesn't include it's own Recovery handler.
Repanic bool
// WaitForDelivery configures whether you want to block the request before moving forward with the response.
// Because fasthttp doesn't include it's own Recovery handler, it will restart the application,
// and event won't be delivered otherwise.
WaitForDelivery bool
// Timeout for the event delivery requests.
Timeout time.Duration
}

func New(options Options) fiber.Handler {
handler := handler{
repanic: options.Repanic,
timeout: time.Second * 2,
waitForDelivery: options.WaitForDelivery,
}

if options.Timeout != 0 {
handler.timeout = options.Timeout
}

return handler.handle
}

func (h *handler) handle(ctx *fiber.Ctx) error {
hub := sentry.CurrentHub().Clone()
scope := hub.Scope()

scope.SetRequest(convert(ctx))
scope.SetRequestBody(ctx.Request().Body())
ctx.Locals(valuesKey, hub)
defer h.recoverWithSentry(hub, ctx)
return ctx.Next()
}

func (h *handler) recoverWithSentry(hub *sentry.Hub, ctx *fiber.Ctx) {
if err := recover(); err != nil {
eventID := hub.RecoverWithContext(
context.WithValue(context.Background(), sentry.RequestContextKey, ctx),
err,
)
if eventID != nil && h.waitForDelivery {
hub.Flush(h.timeout)
}
if h.repanic {
panic(err)

Check warning on line 73 in fiber/sentryfiber.go

View check run for this annotation

Codecov / codecov/patch

fiber/sentryfiber.go#L73

Added line #L73 was not covered by tests
}
}
}

func GetHubFromContext(ctx *fiber.Ctx) *sentry.Hub {
if hub, ok := ctx.Locals(valuesKey).(*sentry.Hub); ok {
return hub
}
return nil

Check warning on line 82 in fiber/sentryfiber.go

View check run for this annotation

Codecov / codecov/patch

fiber/sentryfiber.go#L82

Added line #L82 was not covered by tests
}

func convert(ctx *fiber.Ctx) *http.Request {
defer func() {
if err := recover(); err != nil {
sentry.Logger.Printf("%v", err)
}

Check warning on line 89 in fiber/sentryfiber.go

View check run for this annotation

Codecov / codecov/patch

fiber/sentryfiber.go#L88-L89

Added lines #L88 - L89 were not covered by tests
}()

r := new(http.Request)

r.Method = utils.CopyString(ctx.Method())
uri := ctx.Request().URI()
r.URL, _ = url.Parse(fmt.Sprintf("%s://%s%s", uri.Scheme(), uri.Host(), uri.Path()))

// Headers
r.Header = make(http.Header)
ctx.Request().Header.VisitAll(func(key, value []byte) {
r.Header.Add(string(key), string(value))
})
r.Host = utils.CopyString(ctx.Hostname())

// Env
r.RemoteAddr = ctx.Context().RemoteAddr().String()

// QueryString
r.URL.RawQuery = string(ctx.Request().URI().QueryString())

// Body
r.Body = io.NopCloser(bytes.NewReader(ctx.Request().Body()))

return r
}
Loading
Loading