http.tsx 6.6 KB

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