fasthttp.tsx 7.4 KB

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