Last active
October 21, 2024 13:37
-
-
Save rhcarvalho/66130d1252d4a7b1fbaeacfe3687eaf3 to your computer and use it in GitHub Desktop.
Example of using sentry-go and go-chi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module sentry.io/go/chi-example | |
go 1.13 | |
require ( | |
github.com/getsentry/sentry-go v0.4.0 | |
github.com/go-chi/chi v4.0.3+incompatible | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"log" | |
"net/http" | |
"time" | |
"github.com/getsentry/sentry-go" | |
sentryhttp "github.com/getsentry/sentry-go/http" | |
"github.com/go-chi/chi" | |
"github.com/go-chi/chi/middleware" | |
) | |
func main() { | |
err := sentry.Init(sentry.ClientOptions{ | |
Dsn: "", // Set DSN here or set SENTRY_DSN environment variable | |
Debug: true, | |
}) | |
if err != nil { | |
log.Fatalf("sentry.Init: %s", err) | |
} | |
defer sentry.Flush(time.Second) | |
sentryMiddleware := sentryhttp.New(sentryhttp.Options{ | |
Repanic: true, | |
}) | |
r := chi.NewRouter() | |
r.Use(middleware.Logger) | |
r.Use(middleware.Recoverer) | |
// Important: Chi has a middleware stack and thus it is important to put the | |
// Sentry handler on the appropriate place. If using middleware.Recoverer, | |
// the Sentry middleware must come afterwards (and configure it with | |
// Repanic: true). | |
r.Use(sentryMiddleware.Handle) | |
r.Get("/", func(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte("root.")) | |
}) | |
r.Get("/error", func(w http.ResponseWriter, r *http.Request) { | |
hub := sentry.GetHubFromContext(r.Context()) | |
hub.CaptureException(errors.New("test error")) | |
}) | |
r.Get("/panic", func(w http.ResponseWriter, r *http.Request) { | |
panic("server panic") | |
}) | |
http.ListenAndServe("localhost:3333", r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you! Exactly what I needed to know.