http.tsx 6.4 KB

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