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