http.tsx 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. import {Fragment} from 'react';
  2. import {Alert} from 'sentry/components/alert';
  3. import ExternalLink from 'sentry/components/links/externalLink';
  4. import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
  5. import type {
  6. Docs,
  7. DocsParams,
  8. OnboardingConfig,
  9. } from 'sentry/components/onboarding/gettingStartedDoc/types';
  10. import {
  11. getCrashReportGenericInstallStep,
  12. getCrashReportModalConfigDescription,
  13. getCrashReportModalIntroduction,
  14. } from 'sentry/components/onboarding/gettingStartedDoc/utils/feedbackOnboarding';
  15. import {
  16. feedbackOnboardingJsLoader,
  17. replayOnboardingJsLoader,
  18. } from 'sentry/gettingStartedDocs/javascript/jsLoader/jsLoader';
  19. import {t, tct} from 'sentry/locale';
  20. type Params = DocsParams;
  21. const getConfigureSnippet = (params: Params) => `
  22. import (
  23. "fmt"
  24. "net/http"
  25. "github.com/getsentry/sentry-go"
  26. sentryhttp "github.com/getsentry/sentry-go/http"
  27. )
  28. // To initialize Sentry's handler, you need to initialize Sentry itself beforehand
  29. if err := sentry.Init(sentry.ClientOptions{
  30. Dsn: "${params.dsn.public}",${
  31. params.isPerformanceSelected
  32. ? `
  33. // Set TracesSampleRate to 1.0 to capture 100%
  34. // of transactions for tracing.
  35. // We recommend adjusting this value in production,
  36. TracesSampleRate: 1.0,`
  37. : ''
  38. }
  39. }); err != nil {
  40. fmt.Printf("Sentry initialization failed: %v\\n", err)
  41. }
  42. // Create an instance of sentryhttp
  43. sentryHandler := sentryhttp.New(sentryhttp.Options{})
  44. // Once it's done, you can set up routes and attach the handler as one of your middleware
  45. http.Handle("/", sentryHandler.Handle(&handler{}))
  46. http.HandleFunc("/foo", sentryHandler.HandleFunc(func(rw http.ResponseWriter, r *http.Request) {
  47. panic("y tho")
  48. }))
  49. fmt.Println("Listening and serving HTTP on :3000")
  50. // And run it
  51. if err := http.ListenAndServe(":3000", nil); err != nil {
  52. panic(err)
  53. }`;
  54. const getOptionsSnippet = () => `
  55. // Whether Sentry should repanic after recovery, in most cases it should be set to true,
  56. // and you should gracefully handle http responses.
  57. Repanic bool
  58. // Whether you want to block the request before moving forward with the response.
  59. // Useful, when you want to restart the process after it panics.
  60. WaitForDelivery bool
  61. // Timeout for the event delivery requests.
  62. Timeout time.Duration`;
  63. const getUsageSnippet = () => `
  64. type handler struct{}
  65. func (h *handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  66. if hub := sentry.GetHubFromContext(r.Context()); hub != nil {
  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. }
  72. rw.WriteHeader(http.StatusOK)
  73. }
  74. func enhanceSentryEvent(handler http.HandlerFunc) http.HandlerFunc {
  75. return func(rw http.ResponseWriter, r *http.Request) {
  76. if hub := sentry.GetHubFromContext(r.Context()); hub != nil {
  77. hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt")
  78. }
  79. handler(rw, r)
  80. }
  81. }
  82. // Later in the code
  83. sentryHandler := sentryhttp.New(sentryhttp.Options{
  84. Repanic: true,
  85. })
  86. http.Handle("/", sentryHandler.Handle(&handler{}))
  87. http.HandleFunc("/foo", sentryHandler.HandleFunc(
  88. enhanceSentryEvent(func(rw http.ResponseWriter, r *http.Request) {
  89. panic("y tho")
  90. }),
  91. ))
  92. fmt.Println("Listening and serving HTTP on :3000")
  93. if err := http.ListenAndServe(":3000", nil); err != nil {
  94. panic(err)
  95. }`;
  96. const getBeforeSendSnippet = (params: any) => `
  97. sentry.Init(sentry.ClientOptions{
  98. Dsn: "${params.dsn.public}",
  99. BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
  100. if hint.Context != nil {
  101. if req, ok := hint.Context.Value(sentry.RequestContextKey).(*http.Request); ok {
  102. // You have access to the original Request here
  103. }
  104. }
  105. return event
  106. },
  107. })`;
  108. const onboarding: OnboardingConfig = {
  109. install: () => [
  110. {
  111. type: StepType.INSTALL,
  112. description: tct('Install our Go HTTP SDK using [code:go get]:', {
  113. code: <code />,
  114. }),
  115. configurations: [
  116. {
  117. language: 'bash',
  118. code: 'go get github.com/getsentry/sentry-go/http',
  119. },
  120. ],
  121. },
  122. ],
  123. configure: params => [
  124. {
  125. type: StepType.CONFIGURE,
  126. description: t(
  127. "Import and initialize the Sentry SDK early in your application's setup:"
  128. ),
  129. configurations: [
  130. {
  131. language: 'go',
  132. code: getConfigureSnippet(params),
  133. },
  134. {
  135. description: (
  136. <Fragment>
  137. <strong>{t('Options')}</strong>
  138. <p>
  139. {tct(
  140. '[code:sentryhttp] accepts a struct of [code:Options] that allows you to configure how the handler will behave.',
  141. {code: <code />}
  142. )}
  143. </p>
  144. {t('Currently it respects 3 options:')}
  145. </Fragment>
  146. ),
  147. language: 'go',
  148. code: getOptionsSnippet(),
  149. },
  150. ],
  151. },
  152. {
  153. title: t('Usage'),
  154. description: (
  155. <Fragment>
  156. <p>
  157. {tct(
  158. "[code:sentryhttp] 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.",
  159. {
  160. code: <code />,
  161. sentryHubLink: (
  162. <ExternalLink href="https://pkg.go.dev/github.com/getsentry/sentry-go#Hub" />
  163. ),
  164. }
  165. )}
  166. </p>
  167. <Alert type="info">
  168. {tct(
  169. "Keep in mind that [code:*sentry.Hub] won't be available in middleware attached before [code:sentryhttp]!",
  170. {code: <code />}
  171. )}
  172. </Alert>
  173. </Fragment>
  174. ),
  175. configurations: [
  176. {
  177. language: 'go',
  178. code: getUsageSnippet(),
  179. },
  180. {
  181. description: (
  182. <strong>
  183. {tct('Accessing Request in [beforeSendCode:BeforeSend] callback', {
  184. beforeSendCode: <code />,
  185. })}
  186. </strong>
  187. ),
  188. language: 'go',
  189. code: getBeforeSendSnippet(params),
  190. },
  191. ],
  192. },
  193. ],
  194. verify: () => [],
  195. };
  196. const crashReportOnboarding: OnboardingConfig = {
  197. introduction: () => getCrashReportModalIntroduction(),
  198. install: (params: Params) => getCrashReportGenericInstallStep(params),
  199. configure: () => [
  200. {
  201. type: StepType.CONFIGURE,
  202. description: getCrashReportModalConfigDescription({
  203. link: 'https://docs.sentry.io/platforms/go/guides/http/user-feedback/configuration/#crash-report-modal',
  204. }),
  205. },
  206. ],
  207. verify: () => [],
  208. nextSteps: () => [],
  209. };
  210. const docs: Docs = {
  211. onboarding,
  212. replayOnboardingJsLoader,
  213. crashReportOnboarding,
  214. feedbackOnboardingJsLoader,
  215. };
  216. export default docs;