http.tsx 7.4 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}",
  29. EnableTracing: true,
  30. // Set TracesSampleRate to 1.0 to capture 100%
  31. // of transactions for performance monitoring.
  32. // We recommend adjusting this value in production,
  33. TracesSampleRate: 1.0,
  34. }); err != nil {
  35. fmt.Printf("Sentry initialization failed: %v\n", err)
  36. }
  37. // Create an instance of sentryhttp
  38. sentryHandler := sentryhttp.New(sentryhttp.Options{})
  39. // Once it's done, you can set up routes and attach the handler as one of your middleware
  40. http.Handle("/", sentryHandler.Handle(&handler{}))
  41. http.HandleFunc("/foo", sentryHandler.HandleFunc(func(rw http.ResponseWriter, r *http.Request) {
  42. panic("y tho")
  43. }))
  44. fmt.Println("Listening and serving HTTP on :3000")
  45. // And run it
  46. if err := http.ListenAndServe(":3000", nil); err != nil {
  47. panic(err)
  48. }`;
  49. const getOptionsSnippet = () => `
  50. // Whether Sentry should repanic after recovery, in most cases it should be set to true,
  51. // and you should gracefully handle http responses.
  52. Repanic bool
  53. // Whether you want to block the request before moving forward with the response.
  54. // Useful, when you want to restart the process after it panics.
  55. WaitForDelivery bool
  56. // Timeout for the event delivery requests.
  57. Timeout time.Duration`;
  58. const getUsageSnippet = () => `
  59. type handler struct{}
  60. func (h *handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
  61. if hub := sentry.GetHubFromContext(r.Context()); hub != nil {
  62. hub.WithScope(func(scope *sentry.Scope) {
  63. scope.SetExtra("unwantedQuery", "someQueryDataMaybe")
  64. hub.CaptureMessage("User provided unwanted query string, but we recovered just fine")
  65. })
  66. }
  67. rw.WriteHeader(http.StatusOK)
  68. }
  69. func enhanceSentryEvent(handler http.HandlerFunc) http.HandlerFunc {
  70. return func(rw http.ResponseWriter, r *http.Request) {
  71. if hub := sentry.GetHubFromContext(r.Context()); hub != nil {
  72. hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt")
  73. }
  74. handler(rw, r)
  75. }
  76. }
  77. // Later in the code
  78. sentryHandler := sentryhttp.New(sentryhttp.Options{
  79. Repanic: true,
  80. })
  81. http.Handle("/", sentryHandler.Handle(&handler{}))
  82. http.HandleFunc("/foo", sentryHandler.HandleFunc(
  83. enhanceSentryEvent(func(rw http.ResponseWriter, r *http.Request) {
  84. panic("y tho")
  85. }),
  86. ))
  87. fmt.Println("Listening and serving HTTP on :3000")
  88. if err := http.ListenAndServe(":3000", nil); err != nil {
  89. panic(err)
  90. }`;
  91. const getBeforeSendSnippet = params => `
  92. sentry.Init(sentry.ClientOptions{
  93. Dsn: "${params.dsn}",
  94. BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
  95. if hint.Context != nil {
  96. if req, ok := hint.Context.Value(sentry.RequestContextKey).(*http.Request); ok {
  97. // You have access to the original Request here
  98. }
  99. }
  100. return event
  101. },
  102. })`;
  103. const onboarding: OnboardingConfig = {
  104. install: () => [
  105. {
  106. type: StepType.INSTALL,
  107. description: tct('Install our Go HTTP SDK using [code:go get]:', {
  108. code: <code />,
  109. }),
  110. configurations: [
  111. {
  112. language: 'bash',
  113. code: 'go get github.com/getsentry/sentry-go/http',
  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. '[sentryHttpCode:sentryhttp] accepts a struct of [optionsCode:Options] that allows you to configure how the handler will behave.',
  136. {sentryHttpCode: <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. "[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.",
  154. {
  155. sentryHttpCode: <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 [sentryHttpCode:sentryhttp]!",
  168. {sentryHttpCode: <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. 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. `;