fasthttp.tsx 7.7 KB

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