http.tsx 7.1 KB

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