gin.tsx 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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 replayOnboardingJsLoader from 'sentry/gettingStartedDocs/javascript/jsLoader/jsLoader';
  12. import {t, tct} from 'sentry/locale';
  13. type Params = DocsParams;
  14. const getConfigureSnippet = (params: Params) => `
  15. import (
  16. "fmt"
  17. "net/http"
  18. "github.com/getsentry/sentry-go"
  19. sentrygin "github.com/getsentry/sentry-go/gin"
  20. "github.com/gin-gonic/gin"
  21. )
  22. // To initialize Sentry's handler, you need to initialize Sentry itself beforehand
  23. if err := sentry.Init(sentry.ClientOptions{
  24. Dsn: "${params.dsn}",
  25. EnableTracing: true,
  26. // Set TracesSampleRate to 1.0 to capture 100%
  27. // of transactions for performance monitoring.
  28. // We recommend adjusting this value in production,
  29. TracesSampleRate: 1.0,
  30. }); err != nil {
  31. fmt.Printf("Sentry initialization failed: %v\n", err)
  32. }
  33. // Then create your app
  34. app := gin.Default()
  35. // Once it's done, you can attach the handler as one of your middleware
  36. app.Use(sentrygin.New(sentrygin.Options{}))
  37. // Set up routes
  38. app.GET("/", func(ctx *gin.Context) {
  39. ctx.String(http.StatusOK, "Hello world!")
  40. })
  41. // And run it
  42. app.Run(":3000")`;
  43. const getOptionsSnippet = () => `
  44. // Whether Sentry should repanic after recovery, in most cases it should be set to true,
  45. // as gin.Default includes its own Recovery middleware that handles http responses.
  46. Repanic bool
  47. // Whether you want to block the request before moving forward with the response.
  48. // Because Gin's default "Recovery" handler doesn't restart the application,
  49. // it's safe to either skip this option or set it to "false".
  50. WaitForDelivery bool
  51. // Timeout for the event delivery requests.
  52. Timeout time.Duration`;
  53. const getUsageSnippet = () => `
  54. app := gin.Default()
  55. app.Use(sentrygin.New(sentrygin.Options{
  56. Repanic: true,
  57. }))
  58. app.Use(func(ctx *gin.Context) {
  59. if hub := sentrygin.GetHubFromContext(ctx); hub != nil {
  60. hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt")
  61. }
  62. ctx.Next()
  63. })
  64. app.GET("/", func(ctx *gin.Context) {
  65. if hub := sentrygin.GetHubFromContext(ctx); hub != nil {
  66. hub.WithScope(func(scope *sentry.Scope) {
  67. scope.SetExtra("unwantedQuery", "someQueryDataMaybe")
  68. hub.CaptureMessage("User provided unwanted query string, but we recovered just fine")
  69. })
  70. }
  71. ctx.Status(http.StatusOK)
  72. })
  73. app.GET("/foo", func(ctx *gin.Context) {
  74. // sentrygin handler will catch it just fine. Also, because we attached "someRandomTag"
  75. // in the middleware before, it will be sent through as well
  76. panic("y tho")
  77. })
  78. app.Run(":3000")`;
  79. const getBeforeSendSnippet = params => `
  80. sentry.Init(sentry.ClientOptions{
  81. Dsn: "${params.dsn}",
  82. BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
  83. if hint.Context != nil {
  84. if req, ok := hint.Context.Value(sentry.RequestContextKey).(*http.Request); ok {
  85. // You have access to the original Request here
  86. }
  87. }
  88. return event
  89. },
  90. })`;
  91. const onboarding: OnboardingConfig = {
  92. install: () => [
  93. {
  94. type: StepType.INSTALL,
  95. description: tct('Install our Go Gin SDK using [code:go get]:', {
  96. code: <code />,
  97. }),
  98. configurations: [
  99. {
  100. language: 'bash',
  101. code: 'go get github.com/getsentry/sentry-go/gin',
  102. },
  103. ],
  104. },
  105. ],
  106. configure: params => [
  107. {
  108. type: StepType.CONFIGURE,
  109. description: t(
  110. "Import and initialize the Sentry SDK early in your application's setup:"
  111. ),
  112. configurations: [
  113. {
  114. language: 'go',
  115. code: getConfigureSnippet(params),
  116. },
  117. {
  118. description: (
  119. <Fragment>
  120. <strong>{t('Options')}</strong>
  121. <p>
  122. {tct(
  123. '[sentryGinCode:sentrygin] accepts a struct of [optionsCode:Options] that allows you to configure how the handler will behave.',
  124. {sentryGinCode: <code />, optionsCode: <code />}
  125. )}
  126. </p>
  127. {t('Currently it respects 3 options:')}
  128. </Fragment>
  129. ),
  130. language: 'go',
  131. code: getOptionsSnippet(),
  132. },
  133. ],
  134. },
  135. {
  136. title: t('Usage'),
  137. description: (
  138. <Fragment>
  139. <p>
  140. {tct(
  141. "[sentryGinCode:sentrygin] attaches an instance of [sentryHubLink:*sentry.Hub] to the [ginContextCode:*gin.Context], which makes it available throughout the rest of the request's lifetime. You can access it by using the [getHubFromContextCode:sentrygin.GetHubFromContext()] method on the context itself in any of your proceeding middleware and routes. And it should be used instead of the global [captureMessageCode:sentry.CaptureMessage], [captureExceptionCode:sentry.CaptureException], or any other calls, as it keeps the separation of data between the requests.",
  142. {
  143. sentryGinCode: <code />,
  144. sentryHubLink: (
  145. <ExternalLink href="https://godoc.org/github.com/getsentry/sentry-go#Hub" />
  146. ),
  147. ginContextCode: <code />,
  148. getHubFromContextCode: <code />,
  149. captureMessageCode: <code />,
  150. captureExceptionCode: <code />,
  151. }
  152. )}
  153. </p>
  154. <AlertWithoutMarginBottom>
  155. {tct(
  156. "Keep in mind that [sentryHubCode:*sentry.Hub] won't be available in middleware attached before [sentryGinCode:sentrygin]!",
  157. {sentryGinCode: <code />, sentryHubCode: <code />}
  158. )}
  159. </AlertWithoutMarginBottom>
  160. </Fragment>
  161. ),
  162. configurations: [
  163. {
  164. language: 'go',
  165. code: getUsageSnippet(),
  166. },
  167. {
  168. description: (
  169. <strong>
  170. {tct('Accessing Request in [beforeSendCode:BeforeSend] callback', {
  171. beforeSendCode: <code />,
  172. })}
  173. </strong>
  174. ),
  175. language: 'go',
  176. code: getBeforeSendSnippet(params),
  177. },
  178. ],
  179. },
  180. ],
  181. verify: () => [],
  182. };
  183. const docs: Docs = {
  184. onboarding,
  185. replayOnboardingJsLoader,
  186. };
  187. export default docs;
  188. const AlertWithoutMarginBottom = styled(Alert)`
  189. margin-bottom: 0;
  190. `;