Skip to content

Instantly share code, notes, and snippets.

@rhcarvalho
Last active January 16, 2024 01:17
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhcarvalho/66130d1252d4a7b1fbaeacfe3687eaf3 to your computer and use it in GitHub Desktop.
Save rhcarvalho/66130d1252d4a7b1fbaeacfe3687eaf3 to your computer and use it in GitHub Desktop.
Example of using sentry-go and go-chi
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
)
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)
}
@tamsanh
Copy link

tamsanh commented May 19, 2021

Thank you! Exactly what I needed to know.

@sagafonoff
Copy link

Excellent!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment