echo.tsx 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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.public}",${
  31. params.isPerformanceSelected
  32. ? `
  33. // Set TracesSampleRate to 1.0 to capture 100%
  34. // of transactions for tracing.
  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.public}",
  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. '[code:sentryecho] accepts a struct of [code:Options] that allows you to configure how the handler will behave.',
  139. {code: <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. "[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.",
  157. {
  158. code: <code />,
  159. sentryHubLink: (
  160. <ExternalLink href="https://pkg.go.dev/github.com/getsentry/sentry-go#Hub" />
  161. ),
  162. }
  163. )}
  164. </p>
  165. <AlertWithoutMarginBottom>
  166. {tct(
  167. "Keep in mind that [code:*sentry.Hub] won't be available in middleware attached before [code:sentryecho]!",
  168. {code: <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 crashReportOnboarding: OnboardingConfig = {
  195. introduction: () => getCrashReportModalIntroduction(),
  196. install: (params: Params) => getCrashReportGenericInstallStep(params),
  197. configure: () => [
  198. {
  199. type: StepType.CONFIGURE,
  200. description: getCrashReportModalConfigDescription({
  201. link: 'https://docs.sentry.io/platforms/go/guides/echo/user-feedback/configuration/#crash-report-modal',
  202. }),
  203. },
  204. ],
  205. verify: () => [],
  206. nextSteps: () => [],
  207. };
  208. const docs: Docs = {
  209. onboarding,
  210. replayOnboardingJsLoader,
  211. crashReportOnboarding,
  212. };
  213. export default docs;
  214. const AlertWithoutMarginBottom = styled(Alert)`
  215. margin-bottom: 0;
  216. `;