http.tsx 6.4 KB

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