negroni.tsx 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 Negroni 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/negroni',
  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. sentrynegroni "github.com/getsentry/sentry-go/negroni"
  45. "github.com/urfave/negroni"
  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 := negroni.Classic()
  60. // Once it's done, you can attach the handler as one of your middleware
  61. app.Use(sentrynegroni.New(sentrynegroni.Options{}))
  62. // Set up routes
  63. mux := http.NewServeMux()
  64. mux.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
  65. fmt.Fprintf(w, "Hello world!")
  66. })
  67. app.UseHandler(mux)
  68. // And run it
  69. http.ListenAndServe(":3000", app)
  70. `,
  71. },
  72. {
  73. description: (
  74. <Fragment>
  75. <strong>{t('Options')}</strong>
  76. <p>
  77. {tct(
  78. '[sentryNegroniCode:sentrynegroni] accepts a struct of [optionsCode:Options] that allows you to configure how the handler will behave.',
  79. {sentryNegroniCode: <code />, optionsCode: <code />}
  80. )}
  81. </p>
  82. {t('Currently it respects 3 options:')}
  83. </Fragment>
  84. ),
  85. language: 'go',
  86. code: `
  87. // Whether Sentry should repanic after recovery, in most cases it should be set to true,
  88. // as negroni.Classic includes its own Recovery middleware that handles http responses.
  89. Repanic bool
  90. // Whether you want to block the request before moving forward with the response.
  91. // Because Negroni's default "Recovery" handler doesn't restart the application,
  92. // it's safe to either skip this option or set it to "false".
  93. WaitForDelivery bool
  94. // Timeout for the event delivery requests.
  95. Timeout time.Duration
  96. `,
  97. },
  98. ],
  99. },
  100. {
  101. title: t('Usage'),
  102. description: (
  103. <Fragment>
  104. <p>
  105. {tct(
  106. "[sentryNegroniCode:sentrynegroni] attaches an instance of [sentryHubLink:*sentry.Hub] to the request's context, which makes it available throughout the rest of the request's lifetime. You can access it by using the [getHubFromContextCode:sentry.GetHubFromContext()] method on the request 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.",
  107. {
  108. sentryNegroniCode: <code />,
  109. sentryHubLink: (
  110. <ExternalLink href="https://godoc.org/github.com/getsentry/sentry-go#Hub" />
  111. ),
  112. getHubFromContextCode: <code />,
  113. captureMessageCode: <code />,
  114. captureExceptionCode: <code />,
  115. }
  116. )}
  117. </p>
  118. <AlertWithoutMarginBottom>
  119. {tct(
  120. "Keep in mind that [sentryHubCode:*sentry.Hub] won't be available in middleware attached before [sentryNegroniCode:sentrynegroni]!",
  121. {sentryNegroniCode: <code />, sentryHubCode: <code />}
  122. )}
  123. </AlertWithoutMarginBottom>
  124. </Fragment>
  125. ),
  126. configurations: [
  127. {
  128. language: 'go',
  129. code: `
  130. app := negroni.Classic()
  131. app.Use(sentrynegroni.New(sentrynegroni.Options{
  132. Repanic: true,
  133. }))
  134. app.Use(negroni.HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
  135. hub := sentry.GetHubFromContext(r.Context())
  136. hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt")
  137. next(rw, r)
  138. }))
  139. mux := http.NewServeMux()
  140. mux.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
  141. hub := sentry.GetHubFromContext(r.Context())
  142. hub.WithScope(func(scope *sentry.Scope) {
  143. scope.SetExtra("unwantedQuery", "someQueryDataMaybe")
  144. hub.CaptureMessage("User provided unwanted query string, but we recovered just fine")
  145. })
  146. rw.WriteHeader(http.StatusOK)
  147. })
  148. mux.HandleFunc("/foo", func(rw http.ResponseWriter, r *http.Request) {
  149. // sentrynagroni 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.UseHandler(mux)
  154. http.ListenAndServe(":3000", app)
  155. `,
  156. },
  157. {
  158. description: (
  159. <strong>
  160. {tct('Accessing Request in [beforeSendCode:BeforeSend] callback', {
  161. beforeSendCode: <code />,
  162. })}
  163. </strong>
  164. ),
  165. language: 'go',
  166. code: `
  167. sentry.Init(sentry.ClientOptions{
  168. Dsn: "${dsn}",
  169. BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
  170. if hint.Context != nil {
  171. if req, ok := hint.Context.Value(sentry.RequestContextKey).(*http.Request); ok {
  172. // You have access to the original Request here
  173. }
  174. }
  175. return event
  176. },
  177. })
  178. `,
  179. },
  180. ],
  181. },
  182. {
  183. title: t("Using Negroni's 'panicHandlerFuncCode' Option"),
  184. description: (
  185. <Fragment>
  186. <p>
  187. {tct(
  188. "Negroni provides an option called [panicHandlerFuncCode:PanicHandlerFunc], which lets you 'plug-in' to its default [recoveryCode:Recovery] middleware.",
  189. {
  190. panicHandlerFuncCode: <code />,
  191. recoveryCode: <code />,
  192. }
  193. )}
  194. </p>
  195. <p>
  196. {tct(
  197. "[sentrynegroniCode:sentrynegroni] exports a very barebones implementation, which utilizes it, so if you don't need anything else than just reporting panics to Sentry, you can use it instead, as it's just one line of code!",
  198. {
  199. sentrynegroniCode: <code />,
  200. }
  201. )}
  202. </p>
  203. <p>
  204. {tct(
  205. 'You can still use [beforeSendCode:BeforeSend] and event processors to modify data before delivering it to Sentry, using this method as well.',
  206. {
  207. beforeSendCode: <code />,
  208. }
  209. )}
  210. </p>
  211. </Fragment>
  212. ),
  213. configurations: [
  214. {
  215. language: 'go',
  216. code: `
  217. app := negroni.New()
  218. recovery := negroni.NewRecovery()
  219. recovery.PanicHandlerFunc = sentrynegroni.PanicHandlerFunc
  220. app.Use(recovery)
  221. mux := http.NewServeMux()
  222. mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
  223. panic("y tho")
  224. })
  225. app.UseHandler(mux)
  226. http.ListenAndServe(":3000", app)
  227. `,
  228. },
  229. ],
  230. },
  231. ];
  232. // Configuration End
  233. export function GettingStartedWithNegroni({dsn, ...props}: ModuleProps) {
  234. return <Layout steps={steps({dsn})} {...props} />;
  235. }
  236. export default GettingStartedWithNegroni;
  237. const AlertWithoutMarginBottom = styled(Alert)`
  238. margin-bottom: 0;
  239. `;