negroni.tsx 9.0 KB

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