negroni.tsx 8.2 KB

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