negroni.tsx 9.0 KB

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