http.tsx 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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}",${
  29. params.isPerformanceSelected
  30. ? `
  31. // Set TracesSampleRate to 1.0 to capture 100%
  32. // of transactions for performance monitoring.
  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}",
  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. '[sentryHttpCode:sentryhttp] accepts a struct of [optionsCode:Options] that allows you to configure how the handler will behave.',
  139. {sentryHttpCode: <code />, optionsCode: <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. "[sentryHttpCode: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 [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.",
  157. {
  158. sentryHttpCode: <code />,
  159. sentryHubLink: (
  160. <ExternalLink href="https://pkg.go.dev/github.com/getsentry/sentry-go#Hub" />
  161. ),
  162. getHubFromContextCode: <code />,
  163. captureMessageCode: <code />,
  164. captureExceptionCode: <code />,
  165. }
  166. )}
  167. </p>
  168. <AlertWithoutMarginBottom>
  169. {tct(
  170. "Keep in mind that [sentryHubCode:*sentry.Hub] won't be available in middleware attached before [sentryHttpCode:sentryhttp]!",
  171. {sentryHttpCode: <code />, sentryHubCode: <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. };
  216. export default docs;
  217. const AlertWithoutMarginBottom = styled(Alert)`
  218. margin-bottom: 0;
  219. `;