http.tsx 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 {
  17. feedbackOnboardingJsLoader,
  18. replayOnboardingJsLoader,
  19. } from 'sentry/gettingStartedDocs/javascript/jsLoader/jsLoader';
  20. import {t, tct} from 'sentry/locale';
  21. type Params = DocsParams;
  22. const getConfigureSnippet = (params: Params) => `
  23. import (
  24. "fmt"
  25. "net/http"
  26. "github.com/getsentry/sentry-go"
  27. sentryhttp "github.com/getsentry/sentry-go/http"
  28. )
  29. // To initialize Sentry's handler, you need to initialize Sentry itself beforehand
  30. if err := sentry.Init(sentry.ClientOptions{
  31. Dsn: "${params.dsn.public}",${
  32. params.isPerformanceSelected
  33. ? `
  34. // Set TracesSampleRate to 1.0 to capture 100%
  35. // of transactions for tracing.
  36. // We recommend adjusting this value in production,
  37. TracesSampleRate: 1.0,`
  38. : ''
  39. }
  40. }); err != nil {
  41. fmt.Printf("Sentry initialization failed: %v\\n", err)
  42. }
  43. // Create an instance of sentryhttp
  44. sentryHandler := sentryhttp.New(sentryhttp.Options{})
  45. // Once it's done, you can set up routes and attach the handler as one of your middleware
  46. http.Handle("/", sentryHandler.Handle(&handler{}))
  47. http.HandleFunc("/foo", sentryHandler.HandleFunc(func(rw http.ResponseWriter, r *http.Request) {
  48. panic("y tho")
  49. }))
  50. fmt.Println("Listening and serving HTTP on :3000")
  51. // And run it
  52. if err := http.ListenAndServe(":3000", nil); err != nil {
  53. panic(err)
  54. }`;
  55. const getOptionsSnippet = () => `
  56. // Whether Sentry should repanic after recovery, in most cases it should be set to true,
  57. // and you should gracefully handle http responses.
  58. Repanic bool
  59. // Whether you want to block the request before moving forward with the response.
  60. // Useful, when you want to restart the process after it panics.
  61. WaitForDelivery bool
  62. // Timeout for the event delivery requests.
  63. Timeout time.Duration`;
  64. const getUsageSnippet = () => `
  65. type handler struct{}
  66. func (h *handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  67. if hub := sentry.GetHubFromContext(r.Context()); hub != nil {
  68. hub.WithScope(func(scope *sentry.Scope) {
  69. scope.SetExtra("unwantedQuery", "someQueryDataMaybe")
  70. hub.CaptureMessage("User provided unwanted query string, but we recovered just fine")
  71. })
  72. }
  73. rw.WriteHeader(http.StatusOK)
  74. }
  75. func enhanceSentryEvent(handler http.HandlerFunc) http.HandlerFunc {
  76. return func(rw http.ResponseWriter, r *http.Request) {
  77. if hub := sentry.GetHubFromContext(r.Context()); hub != nil {
  78. hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt")
  79. }
  80. handler(rw, r)
  81. }
  82. }
  83. // Later in the code
  84. sentryHandler := sentryhttp.New(sentryhttp.Options{
  85. Repanic: true,
  86. })
  87. http.Handle("/", sentryHandler.Handle(&handler{}))
  88. http.HandleFunc("/foo", sentryHandler.HandleFunc(
  89. enhanceSentryEvent(func(rw http.ResponseWriter, r *http.Request) {
  90. panic("y tho")
  91. }),
  92. ))
  93. fmt.Println("Listening and serving HTTP on :3000")
  94. if err := http.ListenAndServe(":3000", nil); err != nil {
  95. panic(err)
  96. }`;
  97. const getBeforeSendSnippet = params => `
  98. sentry.Init(sentry.ClientOptions{
  99. Dsn: "${params.dsn.public}",
  100. BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
  101. if hint.Context != nil {
  102. if req, ok := hint.Context.Value(sentry.RequestContextKey).(*http.Request); ok {
  103. // You have access to the original Request here
  104. }
  105. }
  106. return event
  107. },
  108. })`;
  109. const onboarding: OnboardingConfig = {
  110. install: () => [
  111. {
  112. type: StepType.INSTALL,
  113. description: tct('Install our Go HTTP SDK using [code:go get]:', {
  114. code: <code />,
  115. }),
  116. configurations: [
  117. {
  118. language: 'bash',
  119. code: 'go get github.com/getsentry/sentry-go/http',
  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. '[code:sentryhttp] accepts a struct of [code:Options] that allows you to configure how the handler will behave.',
  142. {code: <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. "[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.",
  160. {
  161. code: <code />,
  162. sentryHubLink: (
  163. <ExternalLink href="https://pkg.go.dev/github.com/getsentry/sentry-go#Hub" />
  164. ),
  165. }
  166. )}
  167. </p>
  168. <AlertWithoutMarginBottom>
  169. {tct(
  170. "Keep in mind that [code:*sentry.Hub] won't be available in middleware attached before [code:sentryhttp]!",
  171. {code: <code />}
  172. )}
  173. </AlertWithoutMarginBottom>
  174. </Fragment>
  175. ),
  176. configurations: [
  177. {
  178. language: 'go',
  179. code: getUsageSnippet(),
  180. },
  181. {
  182. description: (
  183. <strong>
  184. {tct('Accessing Request in [beforeSendCode:BeforeSend] callback', {
  185. beforeSendCode: <code />,
  186. })}
  187. </strong>
  188. ),
  189. language: 'go',
  190. code: getBeforeSendSnippet(params),
  191. },
  192. ],
  193. },
  194. ],
  195. verify: () => [],
  196. };
  197. const crashReportOnboarding: OnboardingConfig = {
  198. introduction: () => getCrashReportModalIntroduction(),
  199. install: (params: Params) => getCrashReportGenericInstallStep(params),
  200. configure: () => [
  201. {
  202. type: StepType.CONFIGURE,
  203. description: getCrashReportModalConfigDescription({
  204. link: 'https://docs.sentry.io/platforms/go/guides/http/user-feedback/configuration/#crash-report-modal',
  205. }),
  206. },
  207. ],
  208. verify: () => [],
  209. nextSteps: () => [],
  210. };
  211. const docs: Docs = {
  212. onboarding,
  213. replayOnboardingJsLoader,
  214. crashReportOnboarding,
  215. feedbackOnboardingJsLoader,
  216. };
  217. export default docs;
  218. const AlertWithoutMarginBottom = styled(Alert)`
  219. margin-bottom: 0;
  220. `;