fasthttp.tsx 6.8 KB

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