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

Add Fiber integration #273

Closed
wants to merge 8 commits into from
Closed
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
63 changes: 63 additions & 0 deletions example/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"
"github.com/gofiber/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.ImmutableString(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) {
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)
})

if err := app.Listen(3000); err != nil {
panic(err)
}
}
125 changes: 125 additions & 0 deletions fiber/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
<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

**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"
"github.com/getsentry/sentry-go"
sentryfiber "github.com/getsentry/sentry-go/fiber"
)

// 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 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
},
})
```
127 changes: 127 additions & 0 deletions fiber/sentryfiber.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
package sentryfiber

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

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

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: false,
timeout: time.Second * 2,
waitForDelivery: false,
}

if options.Repanic {
handler.repanic = true
}

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

if options.WaitForDelivery {
handler.waitForDelivery = true
}

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)
}
}
}

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

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

r := new(http.Request)

r.Method = utils.ImmutableString(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.ImmutableString(ctx.Hostname())

// Cookies
ctx.Request().Header.VisitAllCookie(func(key, value []byte) {
r.AddCookie(&http.Cookie{Name: string(key), Value: string(value)})
})

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

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

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

return r
}
Loading