gin.tsx 6.1 KB

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