gin.tsx 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. import {Fragment} from 'react';
  2. import {Alert} from 'sentry/components/core/alert';
  3. import ExternalLink from 'sentry/components/links/externalLink';
  4. import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step';
  5. import type {
  6. Docs,
  7. DocsParams,
  8. OnboardingConfig,
  9. } from 'sentry/components/onboarding/gettingStartedDoc/types';
  10. import {
  11. getCrashReportGenericInstallStep,
  12. getCrashReportModalConfigDescription,
  13. getCrashReportModalIntroduction,
  14. } from 'sentry/components/onboarding/gettingStartedDoc/utils/feedbackOnboarding';
  15. import {
  16. feedbackOnboardingJsLoader,
  17. replayOnboardingJsLoader,
  18. } from 'sentry/gettingStartedDocs/javascript/jsLoader/jsLoader';
  19. import {t, tct} from 'sentry/locale';
  20. type Params = DocsParams;
  21. const getConfigureSnippet = (params: Params) => `
  22. import (
  23. "fmt"
  24. "net/http"
  25. "github.com/getsentry/sentry-go"
  26. sentrygin "github.com/getsentry/sentry-go/gin"
  27. "github.com/gin-gonic/gin"
  28. )
  29. // To initialize Sentry's handler, you need to initialize Sentry itself beforehand
  30. if err := sentry.Init(sentry.ClientOptions{
  31. Dsn: "${params.dsn.public}",${
  32. params.isPerformanceSelected
  33. ? `
  34. EnableTracing: true,
  35. // Set TracesSampleRate to 1.0 to capture 100%
  36. // of transactions for tracing.
  37. // We recommend adjusting this value in production,
  38. TracesSampleRate: 1.0,`
  39. : ''
  40. }
  41. }); err != nil {
  42. fmt.Printf("Sentry initialization failed: %v\\n", err)
  43. }
  44. // Then create your app
  45. app := gin.Default()
  46. // Once it's done, you can attach the handler as one of your middleware
  47. app.Use(sentrygin.New(sentrygin.Options{}))
  48. // Set up routes
  49. app.GET("/", func(ctx *gin.Context) {
  50. ctx.String(http.StatusOK, "Hello world!")
  51. })
  52. // And run it
  53. app.Run(":3000")`;
  54. const getOptionsSnippet = () => `
  55. // Whether Sentry should repanic after recovery, in most cases it should be set to true,
  56. // as gin.Default includes its own Recovery middleware that handles http responses.
  57. Repanic bool
  58. // Whether you want to block the request before moving forward with the response.
  59. // Because Gin's default "Recovery" 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 := gin.Default()
  66. app.Use(sentrygin.New(sentrygin.Options{
  67. Repanic: true,
  68. }))
  69. app.Use(func(ctx *gin.Context) {
  70. if hub := sentrygin.GetHubFromContext(ctx); hub != nil {
  71. hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt")
  72. }
  73. ctx.Next()
  74. })
  75. app.GET("/", func(ctx *gin.Context) {
  76. if hub := sentrygin.GetHubFromContext(ctx); hub != nil {
  77. hub.WithScope(func(scope *sentry.Scope) {
  78. scope.SetExtra("unwantedQuery", "someQueryDataMaybe")
  79. hub.CaptureMessage("User provided unwanted query string, but we recovered just fine")
  80. })
  81. }
  82. ctx.Status(http.StatusOK)
  83. })
  84. app.GET("/foo", func(ctx *gin.Context) {
  85. // sentrygin handler will catch it just fine. Also, because we attached "someRandomTag"
  86. // in the middleware before, it will be sent through as well
  87. panic("y tho")
  88. })
  89. app.Run(":3000")`;
  90. const getBeforeSendSnippet = (params: any) => `
  91. sentry.Init(sentry.ClientOptions{
  92. Dsn: "${params.dsn.public}",
  93. BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
  94. if hint.Context != nil {
  95. if req, ok := hint.Context.Value(sentry.RequestContextKey).(*http.Request); ok {
  96. // You have access to the original Request here
  97. }
  98. }
  99. return event
  100. },
  101. })`;
  102. const onboarding: OnboardingConfig = {
  103. install: () => [
  104. {
  105. type: StepType.INSTALL,
  106. description: tct('Install our Go Gin SDK using [code:go get]:', {
  107. code: <code />,
  108. }),
  109. configurations: [
  110. {
  111. language: 'bash',
  112. code: 'go get github.com/getsentry/sentry-go/gin',
  113. },
  114. ],
  115. },
  116. ],
  117. configure: params => [
  118. {
  119. type: StepType.CONFIGURE,
  120. description: t(
  121. "Import and initialize the Sentry SDK early in your application's setup:"
  122. ),
  123. configurations: [
  124. {
  125. language: 'go',
  126. code: getConfigureSnippet(params),
  127. },
  128. {
  129. description: (
  130. <Fragment>
  131. <strong>{t('Options')}</strong>
  132. <p>
  133. {tct(
  134. '[code:sentrygin] accepts a struct of [code:Options] that allows you to configure how the handler will behave.',
  135. {code: <code />}
  136. )}
  137. </p>
  138. {t('Currently it respects 3 options:')}
  139. </Fragment>
  140. ),
  141. language: 'go',
  142. code: getOptionsSnippet(),
  143. },
  144. ],
  145. },
  146. {
  147. title: t('Usage'),
  148. description: (
  149. <Fragment>
  150. <p>
  151. {tct(
  152. "[code:sentrygin] attaches an instance of [sentryHubLink:*sentry.Hub] to the [code:*gin.Context], which makes it available throughout the rest of the request's lifetime. You can access it by using the [code:sentrygin.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.",
  153. {
  154. code: <code />,
  155. sentryHubLink: (
  156. <ExternalLink href="https://pkg.go.dev/github.com/getsentry/sentry-go#Hub" />
  157. ),
  158. }
  159. )}
  160. </p>
  161. <Alert type="info">
  162. {tct(
  163. "Keep in mind that [code:*sentry.Hub] won't be available in middleware attached before [code:sentrygin]!",
  164. {code: <code />}
  165. )}
  166. </Alert>
  167. </Fragment>
  168. ),
  169. configurations: [
  170. {
  171. language: 'go',
  172. code: getUsageSnippet(),
  173. },
  174. {
  175. description: (
  176. <strong>
  177. {tct('Accessing Request in [beforeSendCode:BeforeSend] callback', {
  178. beforeSendCode: <code />,
  179. })}
  180. </strong>
  181. ),
  182. language: 'go',
  183. code: getBeforeSendSnippet(params),
  184. },
  185. ],
  186. },
  187. ],
  188. verify: () => [],
  189. };
  190. const crashReportOnboarding: OnboardingConfig = {
  191. introduction: () => getCrashReportModalIntroduction(),
  192. install: (params: Params) => getCrashReportGenericInstallStep(params),
  193. configure: () => [
  194. {
  195. type: StepType.CONFIGURE,
  196. description: getCrashReportModalConfigDescription({
  197. link: 'https://docs.sentry.io/platforms/go/guides/gin/user-feedback/configuration/#crash-report-modal',
  198. }),
  199. },
  200. ],
  201. verify: () => [],
  202. nextSteps: () => [],
  203. };
  204. const docs: Docs = {
  205. onboarding,
  206. replayOnboardingJsLoader,
  207. crashReportOnboarding,
  208. feedbackOnboardingJsLoader,
  209. };
  210. export default docs;