fasthttp.tsx 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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 {
  17. feedbackOnboardingJsLoader,
  18. replayOnboardingJsLoader,
  19. } from 'sentry/gettingStartedDocs/javascript/jsLoader/jsLoader';
  20. import {t, tct} from 'sentry/locale';
  21. type Params = DocsParams;
  22. const getConfigureSnippet = (params: Params) => `
  23. import (
  24. "fmt"
  25. "net/http"
  26. "github.com/getsentry/sentry-go"
  27. sentryfasthttp "github.com/getsentry/sentry-go/fasthttp"
  28. )
  29. // To initialize Sentry's handler, you need to initialize Sentry itself beforehand
  30. if err := sentry.Init(sentry.ClientOptions{
  31. Dsn: "${params.dsn.public}",${
  32. params.isPerformanceSelected
  33. ? `
  34. EnableTracing: true,
  35. // Set TracesSampleRate to 1.0 to capture 100%
  36. // of transactions for tracing.
  37. // We recommend adjusting this value in production,
  38. TracesSampleRate: 1.0,`
  39. : ''
  40. }
  41. }); err != nil {
  42. fmt.Printf("Sentry initialization failed: %v\\n", err)
  43. }
  44. // Create an instance of sentryfasthttp
  45. sentryHandler := sentryfasthttp.New(sentryfasthttp.Options{})
  46. // After creating the instance, you can attach the handler as one of your middleware
  47. fastHTTPHandler := sentryHandler.Handle(func(ctx *fasthttp.RequestCtx) {
  48. panic("y tho")
  49. })
  50. fmt.Println("Listening and serving HTTP on :3000")
  51. // And run it
  52. if err := fasthttp.ListenAndServe(":3000", fastHTTPHandler); err != nil {
  53. panic(err)
  54. }`;
  55. const getOptionsSnippet = () => `
  56. // Repanic configures whether Sentry should repanic after recovery, in most cases, it defaults to false,
  57. // as fasthttp doesn't include its own Recovery handler.
  58. Repanic bool
  59. // WaitForDelivery configures whether you want to block the request before moving forward with the response.
  60. // Because fasthttp doesn't include its own "Recovery" handler, it will restart the application,
  61. // and the event won't be delivered otherwise.
  62. WaitForDelivery bool
  63. // Timeout for the event delivery requests.
  64. Timeout time.Duration`;
  65. const getUsageSnippet = () => `
  66. func enhanceSentryEvent(handler fasthttp.RequestHandler) fasthttp.RequestHandler {
  67. return func(ctx *fasthttp.RequestCtx) {
  68. if hub := sentryfasthttp.GetHubFromContext(ctx); hub != nil {
  69. hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt")
  70. }
  71. handler(ctx)
  72. }
  73. }
  74. // Later in the code
  75. sentryHandler := sentryfasthttp.New(sentryfasthttp.Options{
  76. Repanic: true,
  77. WaitForDelivery: true,
  78. })
  79. defaultHandler := func(ctx *fasthttp.RequestCtx) {
  80. if hub := sentryfasthttp.GetHubFromContext(ctx); hub != nil {
  81. hub.WithScope(func(scope *sentry.Scope) {
  82. scope.SetExtra("unwantedQuery", "someQueryDataMaybe")
  83. hub.CaptureMessage("User provided unwanted query string, but we recovered just fine")
  84. })
  85. }
  86. ctx.SetStatusCode(fasthttp.StatusOK)
  87. }
  88. fooHandler := enhanceSentryEvent(func(ctx *fasthttp.RequestCtx) {
  89. panic("y tho")
  90. })
  91. fastHTTPHandler := func(ctx *fasthttp.RequestCtx) {
  92. switch string(ctx.Path()) {
  93. case "/foo":
  94. fooHandler(ctx)
  95. default:
  96. defaultHandler(ctx)
  97. }
  98. }
  99. fmt.Println("Listening and serving HTTP on :3000")
  100. if err := fasthttp.ListenAndServe(":3000", sentryHandler.Handle(fastHTTPHandler)); err != nil {
  101. panic(err)
  102. }`;
  103. const getBeforeSendSnippet = params => `
  104. sentry.Init(sentry.ClientOptions{
  105. Dsn: "${params.dsn.public}",
  106. BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
  107. if hint.Context != nil {
  108. if ctx, ok := hint.Context.Value(sentry.RequestContextKey).(*fasthttp.RequestCtx); ok {
  109. // You have access to the original Context if it panicked
  110. fmt.Println(string(ctx.Request.Host()))
  111. }
  112. }
  113. return event
  114. },
  115. })`;
  116. const onboarding: OnboardingConfig = {
  117. install: () => [
  118. {
  119. type: StepType.INSTALL,
  120. description: tct('Install our Go FastHTTP SDK using [code:go get]:', {
  121. code: <code />,
  122. }),
  123. configurations: [
  124. {
  125. language: 'bash',
  126. code: 'go get github.com/getsentry/sentry-go/fasthttp',
  127. },
  128. ],
  129. },
  130. ],
  131. configure: params => [
  132. {
  133. type: StepType.CONFIGURE,
  134. description: t(
  135. "Import and initialize the Sentry SDK early in your application's setup:"
  136. ),
  137. configurations: [
  138. {
  139. language: 'go',
  140. code: getConfigureSnippet(params),
  141. },
  142. {
  143. description: (
  144. <Fragment>
  145. <strong>{t('Options')}</strong>
  146. <p>
  147. {tct(
  148. '[code:sentryfasthttp] accepts a struct of [code:Options] that allows you to configure how the handler will behave.',
  149. {code: <code />}
  150. )}
  151. </p>
  152. {t('Currently it respects 3 options:')}
  153. </Fragment>
  154. ),
  155. language: 'go',
  156. code: getOptionsSnippet(),
  157. },
  158. ],
  159. },
  160. {
  161. title: t('Usage'),
  162. description: (
  163. <Fragment>
  164. <p>
  165. {tct(
  166. "[code:sentryfasthttp] 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 [code:sentryfasthttp.GetHubFromContext()] method on the context itself in any of your proceeding middleware and routes. And it should be used instead of the global [code:sentry.CaptureMessage], [code:sentry.CaptureException], or any other calls, as it keeps the separation of data between the requests.",
  167. {
  168. sentryHubLink: (
  169. <ExternalLink href="https://pkg.go.dev/github.com/getsentry/sentry-go#Hub" />
  170. ),
  171. code: <code />,
  172. }
  173. )}
  174. </p>
  175. <AlertWithoutMarginBottom>
  176. {tct(
  177. "Keep in mind that [code:*sentry.Hub] won't be available in middleware attached before [code:sentryfasthttp]!",
  178. {code: <code />}
  179. )}
  180. </AlertWithoutMarginBottom>
  181. </Fragment>
  182. ),
  183. configurations: [
  184. {
  185. language: 'go',
  186. code: getUsageSnippet(),
  187. },
  188. {
  189. description: (
  190. <strong>
  191. {tct('Accessing Request in [beforeSendCode:BeforeSend] callback', {
  192. beforeSendCode: <code />,
  193. })}
  194. </strong>
  195. ),
  196. language: 'go',
  197. code: getBeforeSendSnippet(params),
  198. },
  199. ],
  200. },
  201. ],
  202. verify: () => [],
  203. };
  204. const crashReportOnboarding: OnboardingConfig = {
  205. introduction: () => getCrashReportModalIntroduction(),
  206. install: (params: Params) => getCrashReportGenericInstallStep(params),
  207. configure: () => [
  208. {
  209. type: StepType.CONFIGURE,
  210. description: getCrashReportModalConfigDescription({
  211. link: 'https://docs.sentry.io/platforms/go/guides/fasthttp/user-feedback/configuration/#crash-report-modal',
  212. }),
  213. },
  214. ],
  215. verify: () => [],
  216. nextSteps: () => [],
  217. };
  218. const docs: Docs = {
  219. onboarding,
  220. replayOnboardingJsLoader,
  221. crashReportOnboarding,
  222. feedbackOnboardingJsLoader,
  223. };
  224. export default docs;
  225. const AlertWithoutMarginBottom = styled(Alert)`
  226. margin-bottom: 0;
  227. `;