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