gin.tsx 6.3 KB

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