http.tsx 6.7 KB

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