gin.tsx 6.8 KB

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