negroni.tsx 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import {Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import {Alert} from 'sentry/components/alert';
  4. import ExternalLink from 'sentry/components/links/externalLink';
  5. import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout';
  6. import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation';
  7. import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
  8. import {t, tct} from 'sentry/locale';
  9. // Configuration Start
  10. export const steps = ({
  11. dsn,
  12. }: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [
  13. {
  14. type: StepType.INSTALL,
  15. description: (
  16. <p>
  17. {tct('Install our Go Negroni SDK using [code:go get]:', {
  18. code: <code />,
  19. })}
  20. </p>
  21. ),
  22. configurations: [
  23. {
  24. language: 'bash',
  25. code: 'go get github.com/getsentry/sentry-go/negroni',
  26. },
  27. ],
  28. },
  29. {
  30. type: StepType.CONFIGURE,
  31. description: t(
  32. "Import and initialize the Sentry SDK early in your application's setup:"
  33. ),
  34. configurations: [
  35. {
  36. language: 'go',
  37. code: `
  38. import (
  39. "fmt"
  40. "net/http"
  41. "github.com/getsentry/sentry-go"
  42. sentrynegroni "github.com/getsentry/sentry-go/negroni"
  43. "github.com/urfave/negroni"
  44. )
  45. // To initialize Sentry's handler, you need to initialize Sentry itself beforehand
  46. if err := sentry.Init(sentry.ClientOptions{
  47. Dsn: "${dsn}",
  48. EnableTracing: true,
  49. // Set TracesSampleRate to 1.0 to capture 100%
  50. // of transactions for performance monitoring.
  51. // We recommend adjusting this value in production,
  52. TracesSampleRate: 1.0,
  53. }); err != nil {
  54. fmt.Printf("Sentry initialization failed: %v\n", err)
  55. }
  56. // Then create your app
  57. app := negroni.Classic()
  58. // Once it's done, you can attach the handler as one of your middleware
  59. app.Use(sentrynegroni.New(sentrynegroni.Options{}))
  60. // Set up routes
  61. mux := http.NewServeMux()
  62. mux.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
  63. fmt.Fprintf(w, "Hello world!")
  64. })
  65. app.UseHandler(mux)
  66. // And run it
  67. http.ListenAndServe(":3000", app)
  68. `,
  69. },
  70. {
  71. description: (
  72. <Fragment>
  73. <strong>{t('Options')}</strong>
  74. <p>
  75. {tct(
  76. '[sentryNegroniCode:sentrynegroni] accepts a struct of [optionsCode:Options] that allows you to configure how the handler will behave.',
  77. {sentryNegroniCode: <code />, optionsCode: <code />}
  78. )}
  79. </p>
  80. {t('Currently it respects 3 options:')}
  81. </Fragment>
  82. ),
  83. language: 'go',
  84. code: `
  85. // Whether Sentry should repanic after recovery, in most cases it should be set to true,
  86. // as negroni.Classic includes its own Recovery middleware that handles http responses.
  87. Repanic bool
  88. // Whether you want to block the request before moving forward with the response.
  89. // Because Negroni's default "Recovery" handler doesn't restart the application,
  90. // it's safe to either skip this option or set it to "false".
  91. WaitForDelivery bool
  92. // Timeout for the event delivery requests.
  93. Timeout time.Duration
  94. `,
  95. },
  96. ],
  97. },
  98. {
  99. title: t('Usage'),
  100. description: (
  101. <Fragment>
  102. <p>
  103. {tct(
  104. "[sentryNegroniCode:sentrynegroni] attaches an instance of [sentryHubLink:*sentry.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 [getHubFromContextCode:sentry.GetHubFromContext()] method on the request itself in any of your proceeding middleware and routes. And it should be used instead of the global [captureMessageCode:sentry.CaptureMessage], [captureExceptionCode:sentry.CaptureException], or any other calls, as it keeps the separation of data between the requests.",
  105. {
  106. sentryNegroniCode: <code />,
  107. sentryHubLink: (
  108. <ExternalLink href="https://godoc.org/github.com/getsentry/sentry-go#Hub" />
  109. ),
  110. getHubFromContextCode: <code />,
  111. captureMessageCode: <code />,
  112. captureExceptionCode: <code />,
  113. }
  114. )}
  115. </p>
  116. <AlertWithoutMarginBottom>
  117. {tct(
  118. "Keep in mind that [sentryHubCode:*sentry.Hub] won't be available in middleware attached before [sentryNegroniCode:sentrynegroni]!",
  119. {sentryNegroniCode: <code />, sentryHubCode: <code />}
  120. )}
  121. </AlertWithoutMarginBottom>
  122. </Fragment>
  123. ),
  124. configurations: [
  125. {
  126. language: 'go',
  127. code: `
  128. app := negroni.Classic()
  129. app.Use(sentrynegroni.New(sentrynegroni.Options{
  130. Repanic: true,
  131. }))
  132. app.Use(negroni.HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
  133. hub := sentry.GetHubFromContext(r.Context())
  134. hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt")
  135. next(rw, r)
  136. }))
  137. mux := http.NewServeMux()
  138. mux.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
  139. hub := sentry.GetHubFromContext(r.Context())
  140. hub.WithScope(func(scope *sentry.Scope) {
  141. scope.SetExtra("unwantedQuery", "someQueryDataMaybe")
  142. hub.CaptureMessage("User provided unwanted query string, but we recovered just fine")
  143. })
  144. rw.WriteHeader(http.StatusOK)
  145. })
  146. mux.HandleFunc("/foo", func(rw http.ResponseWriter, r *http.Request) {
  147. // sentrynagroni handler will catch it just fine. Also, because we attached "someRandomTag"
  148. // in the middleware before, it will be sent through as well
  149. panic("y tho")
  150. })
  151. app.UseHandler(mux)
  152. http.ListenAndServe(":3000", app)
  153. `,
  154. },
  155. {
  156. description: (
  157. <strong>
  158. {tct('Accessing Request in [beforeSendCode:BeforeSend] callback', {
  159. beforeSendCode: <code />,
  160. })}
  161. </strong>
  162. ),
  163. language: 'go',
  164. code: `
  165. sentry.Init(sentry.ClientOptions{
  166. Dsn: "${dsn}",
  167. BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
  168. if hint.Context != nil {
  169. if req, ok := hint.Context.Value(sentry.RequestContextKey).(*http.Request); ok {
  170. // You have access to the original Request here
  171. }
  172. }
  173. return event
  174. },
  175. })
  176. `,
  177. },
  178. ],
  179. },
  180. {
  181. title: t("Using Negroni's 'panicHandlerFuncCode' Option"),
  182. description: (
  183. <Fragment>
  184. <p>
  185. {tct(
  186. "Negroni provides an option called [panicHandlerFuncCode:PanicHandlerFunc], which lets you 'plug-in' to its default [recoveryCode:Recovery] middleware.",
  187. {
  188. panicHandlerFuncCode: <code />,
  189. recoveryCode: <code />,
  190. }
  191. )}
  192. </p>
  193. <p>
  194. {tct(
  195. "[sentrynegroniCode:sentrynegroni] exports a very barebones implementation, which utilizes it, so if you don't need anything else than just reporting panics to Sentry, you can use it instead, as it's just one line of code!",
  196. {
  197. sentrynegroniCode: <code />,
  198. }
  199. )}
  200. </p>
  201. <p>
  202. {tct(
  203. 'You can still use [beforeSendCode:BeforeSend] and event processors to modify data before delivering it to Sentry, using this method as well.',
  204. {
  205. beforeSendCode: <code />,
  206. }
  207. )}
  208. </p>
  209. </Fragment>
  210. ),
  211. configurations: [
  212. {
  213. language: 'go',
  214. code: `
  215. app := negroni.New()
  216. recovery := negroni.NewRecovery()
  217. recovery.PanicHandlerFunc = sentrynegroni.PanicHandlerFunc
  218. app.Use(recovery)
  219. mux := http.NewServeMux()
  220. mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
  221. panic("y tho")
  222. })
  223. app.UseHandler(mux)
  224. http.ListenAndServe(":3000", app)
  225. `,
  226. },
  227. ],
  228. },
  229. ];
  230. // Configuration End
  231. export function GettingStartedWithNegroni({dsn, ...props}: ModuleProps) {
  232. return <Layout steps={steps({dsn})} {...props} />;
  233. }
  234. export default GettingStartedWithNegroni;
  235. const AlertWithoutMarginBottom = styled(Alert)`
  236. margin-bottom: 0;
  237. `;