fasthttp.tsx 7.0 KB

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