gin.tsx 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. sentrygin "github.com/getsentry/sentry-go/gin"
  28. "github.com/gin-gonic/gin"
  29. )
  30. // To initialize Sentry's handler, you need to initialize Sentry itself beforehand
  31. if err := sentry.Init(sentry.ClientOptions{
  32. Dsn: "${params.dsn.public}",${
  33. params.isPerformanceSelected
  34. ? `
  35. EnableTracing: true,
  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 := gin.Default()
  47. // Once it's done, you can attach the handler as one of your middleware
  48. app.Use(sentrygin.New(sentrygin.Options{}))
  49. // Set up routes
  50. app.GET("/", func(ctx *gin.Context) {
  51. ctx.String(http.StatusOK, "Hello world!")
  52. })
  53. // And run it
  54. app.Run(":3000")`;
  55. const getOptionsSnippet = () => `
  56. // Whether Sentry should repanic after recovery, in most cases it should be set to true,
  57. // as gin.Default includes its own Recovery middleware that handles http responses.
  58. Repanic bool
  59. // Whether you want to block the request before moving forward with the response.
  60. // Because Gin's default "Recovery" handler doesn't restart the application,
  61. // it's safe to either skip this option or set it to "false".
  62. WaitForDelivery bool
  63. // Timeout for the event delivery requests.
  64. Timeout time.Duration`;
  65. const getUsageSnippet = () => `
  66. app := gin.Default()
  67. app.Use(sentrygin.New(sentrygin.Options{
  68. Repanic: true,
  69. }))
  70. app.Use(func(ctx *gin.Context) {
  71. if hub := sentrygin.GetHubFromContext(ctx); hub != nil {
  72. hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt")
  73. }
  74. ctx.Next()
  75. })
  76. app.GET("/", func(ctx *gin.Context) {
  77. if hub := sentrygin.GetHubFromContext(ctx); hub != nil {
  78. hub.WithScope(func(scope *sentry.Scope) {
  79. scope.SetExtra("unwantedQuery", "someQueryDataMaybe")
  80. hub.CaptureMessage("User provided unwanted query string, but we recovered just fine")
  81. })
  82. }
  83. ctx.Status(http.StatusOK)
  84. })
  85. app.GET("/foo", func(ctx *gin.Context) {
  86. // sentrygin handler will catch it just fine. Also, because we attached "someRandomTag"
  87. // in the middleware before, it will be sent through as well
  88. panic("y tho")
  89. })
  90. app.Run(":3000")`;
  91. const getBeforeSendSnippet = params => `
  92. sentry.Init(sentry.ClientOptions{
  93. Dsn: "${params.dsn.public}",
  94. BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
  95. if hint.Context != nil {
  96. if req, ok := hint.Context.Value(sentry.RequestContextKey).(*http.Request); ok {
  97. // You have access to the original Request here
  98. }
  99. }
  100. return event
  101. },
  102. })`;
  103. const onboarding: OnboardingConfig = {
  104. install: () => [
  105. {
  106. type: StepType.INSTALL,
  107. description: tct('Install our Go Gin SDK using [code:go get]:', {
  108. code: <code />,
  109. }),
  110. configurations: [
  111. {
  112. language: 'bash',
  113. code: 'go get github.com/getsentry/sentry-go/gin',
  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. '[code:sentrygin] accepts a struct of [code:Options] that allows you to configure how the handler will behave.',
  136. {code: <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. "[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.",
  154. {
  155. code: <code />,
  156. sentryHubLink: (
  157. <ExternalLink href="https://pkg.go.dev/github.com/getsentry/sentry-go#Hub" />
  158. ),
  159. }
  160. )}
  161. </p>
  162. <AlertWithoutMarginBottom>
  163. {tct(
  164. "Keep in mind that [code:*sentry.Hub] won't be available in middleware attached before [code:sentrygin]!",
  165. {code: <code />}
  166. )}
  167. </AlertWithoutMarginBottom>
  168. </Fragment>
  169. ),
  170. configurations: [
  171. {
  172. language: 'go',
  173. code: getUsageSnippet(),
  174. },
  175. {
  176. description: (
  177. <strong>
  178. {tct('Accessing Request in [beforeSendCode:BeforeSend] callback', {
  179. beforeSendCode: <code />,
  180. })}
  181. </strong>
  182. ),
  183. language: 'go',
  184. code: getBeforeSendSnippet(params),
  185. },
  186. ],
  187. },
  188. ],
  189. verify: () => [],
  190. };
  191. const crashReportOnboarding: OnboardingConfig = {
  192. introduction: () => getCrashReportModalIntroduction(),
  193. install: (params: Params) => getCrashReportGenericInstallStep(params),
  194. configure: () => [
  195. {
  196. type: StepType.CONFIGURE,
  197. description: getCrashReportModalConfigDescription({
  198. link: 'https://docs.sentry.io/platforms/go/guides/gin/user-feedback/configuration/#crash-report-modal',
  199. }),
  200. },
  201. ],
  202. verify: () => [],
  203. nextSteps: () => [],
  204. };
  205. const docs: Docs = {
  206. onboarding,
  207. replayOnboardingJsLoader,
  208. crashReportOnboarding,
  209. feedbackOnboardingJsLoader,
  210. };
  211. export default docs;
  212. const AlertWithoutMarginBottom = styled(Alert)`
  213. margin-bottom: 0;
  214. `;