negroni.tsx 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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.public}",${
  30. params.isPerformanceSelected
  31. ? `
  32. // Set TracesSampleRate to 1.0 to capture 100%
  33. // of transactions for tracing.
  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.public}",
  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. '[code:sentrynegroni] accepts a struct of [code:Options] that allows you to configure how the handler will behave.',
  145. {code: <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. "[code: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 [code:sentry.GetHubFromContext()] method on the request itself in any of your proceeding middleware and routes. And it should be used instead of the global [code:sentry.CaptureMessage], [code:sentry.CaptureException], or any other calls, as it keeps the separation of data between the requests.",
  163. {
  164. code: <code />,
  165. sentryHubLink: (
  166. <ExternalLink href="https://pkg.go.dev/github.com/getsentry/sentry-go#Hub" />
  167. ),
  168. }
  169. )}
  170. </p>
  171. <AlertWithoutMarginBottom>
  172. {tct(
  173. "Keep in mind that [code:*sentry.Hub] won't be available in middleware attached before [code:sentrynegroni]!",
  174. {code: <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 [code:PanicHandlerFunc], which lets you 'plug-in' to its default [code:Recovery] middleware.",
  204. {
  205. code: <code />,
  206. }
  207. )}
  208. </p>
  209. <p>
  210. {tct(
  211. "[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!",
  212. {
  213. sentrynegroniCode: <code />,
  214. }
  215. )}
  216. </p>
  217. <p>
  218. {tct(
  219. 'You can still use [beforeSendCode:BeforeSend] and event processors to modify data before delivering it to Sentry, using this method as well.',
  220. {
  221. beforeSendCode: <code />,
  222. }
  223. )}
  224. </p>
  225. </Fragment>
  226. ),
  227. configurations: [
  228. {
  229. language: 'go',
  230. code: getPanicHandlerSnippet(),
  231. },
  232. ],
  233. },
  234. ],
  235. verify: () => [],
  236. };
  237. const crashReportOnboarding: OnboardingConfig = {
  238. introduction: () => getCrashReportModalIntroduction(),
  239. install: (params: Params) => getCrashReportGenericInstallStep(params),
  240. configure: () => [
  241. {
  242. type: StepType.CONFIGURE,
  243. description: getCrashReportModalConfigDescription({
  244. link: 'https://docs.sentry.io/platforms/go/guides/negroni/user-feedback/configuration/#crash-report-modal',
  245. }),
  246. },
  247. ],
  248. verify: () => [],
  249. nextSteps: () => [],
  250. };
  251. const docs: Docs = {
  252. onboarding,
  253. replayOnboardingJsLoader,
  254. crashReportOnboarding,
  255. };
  256. export default docs;
  257. const AlertWithoutMarginBottom = styled(Alert)`
  258. margin-bottom: 0;
  259. `;