gin.tsx 6.1 KB

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