fasthttp.tsx 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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}",${
  29. params.isPerformanceSelected
  30. ? `
  31. EnableTracing: true,
  32. // Set TracesSampleRate to 1.0 to capture 100%
  33. // of transactions for performance monitoring.
  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}",
  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. '[sentryfasthttpCode:sentryfasthttp] accepts a struct of [optionsCode:Options] that allows you to configure how the handler will behave.',
  146. {sentryfasthttpCode: <code />, optionsCode: <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. "[sentryfasthttpCode: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 [getHubFromContextCode:sentryfasthttp.GetHubFromContext()] method on the context 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.",
  164. {
  165. sentryfasthttpCode: <code />,
  166. sentryHubLink: (
  167. <ExternalLink href="https://pkg.go.dev/github.com/getsentry/sentry-go#Hub" />
  168. ),
  169. getHubFromContextCode: <code />,
  170. captureMessageCode: <code />,
  171. captureExceptionCode: <code />,
  172. }
  173. )}
  174. </p>
  175. <AlertWithoutMarginBottom>
  176. {tct(
  177. "Keep in mind that [sentryHubCode:*sentry.Hub] won't be available in middleware attached before [sentryfasthttpCode:sentryfasthttp]!",
  178. {sentryfasthttpCode: <code />, sentryHubCode: <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. };
  223. export default docs;
  224. const AlertWithoutMarginBottom = styled(Alert)`
  225. margin-bottom: 0;
  226. `;