recovery.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package gin
  5. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log"
  11. "net"
  12. "net/http"
  13. "net/http/httputil"
  14. "os"
  15. "runtime"
  16. "strings"
  17. "time"
  18. )
  19. var (
  20. dunno = []byte("???")
  21. centerDot = []byte("·")
  22. dot = []byte(".")
  23. slash = []byte("/")
  24. )
  25. // RecoveryFunc defines the function passable to CustomRecovery.
  26. type RecoveryFunc func(c *Context, err any)
  27. // Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
  28. func Recovery() HandlerFunc {
  29. return RecoveryWithWriter(DefaultErrorWriter)
  30. }
  31. // CustomRecovery returns a middleware that recovers from any panics and calls the provided handle func to handle it.
  32. func CustomRecovery(handle RecoveryFunc) HandlerFunc {
  33. return RecoveryWithWriter(DefaultErrorWriter, handle)
  34. }
  35. // RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.
  36. func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc {
  37. if len(recovery) > 0 {
  38. return CustomRecoveryWithWriter(out, recovery[0])
  39. }
  40. return CustomRecoveryWithWriter(out, defaultHandleRecovery)
  41. }
  42. // CustomRecoveryWithWriter returns a middleware for a given writer that recovers from any panics and calls the provided handle func to handle it.
  43. func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc {
  44. var logger *log.Logger
  45. if out != nil {
  46. logger = log.New(out, "\n\n\x1b[31m", log.LstdFlags)
  47. }
  48. return func(c *Context) {
  49. defer func() {
  50. if err := recover(); err != nil {
  51. // Check for a broken connection, as it is not really a
  52. // condition that warrants a panic stack trace.
  53. var brokenPipe bool
  54. if ne, ok := err.(*net.OpError); ok {
  55. var se *os.SyscallError
  56. if errors.As(ne, &se) {
  57. seStr := strings.ToLower(se.Error())
  58. if strings.Contains(seStr, "broken pipe") ||
  59. strings.Contains(seStr, "connection reset by peer") {
  60. brokenPipe = true
  61. }
  62. }
  63. }
  64. if logger != nil {
  65. stack := stack(3)
  66. httpRequest, _ := httputil.DumpRequest(c.Request, false)
  67. headers := strings.Split(string(httpRequest), "\r\n")
  68. for idx, header := range headers {
  69. current := strings.Split(header, ":")
  70. if current[0] == "Authorization" {
  71. headers[idx] = current[0] + ": *"
  72. }
  73. }
  74. headersToStr := strings.Join(headers, "\r\n")
  75. if brokenPipe {
  76. logger.Printf("%s\n%s%s", err, headersToStr, reset)
  77. } else if IsDebugging() {
  78. logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s",
  79. timeFormat(time.Now()), headersToStr, err, stack, reset)
  80. } else {
  81. logger.Printf("[Recovery] %s panic recovered:\n%s\n%s%s",
  82. timeFormat(time.Now()), err, stack, reset)
  83. }
  84. }
  85. if brokenPipe {
  86. // If the connection is dead, we can't write a status to it.
  87. c.Error(err.(error)) //nolint: errcheck
  88. c.Abort()
  89. } else {
  90. handle(c, err)
  91. }
  92. }
  93. }()
  94. c.Next()
  95. }
  96. }
  97. func defaultHandleRecovery(c *Context, _ any) {
  98. c.AbortWithStatus(http.StatusInternalServerError)
  99. }
  100. // stack returns a nicely formatted stack frame, skipping skip frames.
  101. func stack(skip int) []byte {
  102. buf := new(bytes.Buffer) // the returned data
  103. // As we loop, we open files and read them. These variables record the currently
  104. // loaded file.
  105. var lines [][]byte
  106. var lastFile string
  107. for i := skip; ; i++ { // Skip the expected number of frames
  108. pc, file, line, ok := runtime.Caller(i)
  109. if !ok {
  110. break
  111. }
  112. // Print this much at least. If we can't find the source, it won't show.
  113. fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
  114. if file != lastFile {
  115. data, err := os.ReadFile(file)
  116. if err != nil {
  117. continue
  118. }
  119. lines = bytes.Split(data, []byte{'\n'})
  120. lastFile = file
  121. }
  122. fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line))
  123. }
  124. return buf.Bytes()
  125. }
  126. // source returns a space-trimmed slice of the n'th line.
  127. func source(lines [][]byte, n int) []byte {
  128. n-- // in stack trace, lines are 1-indexed but our array is 0-indexed
  129. if n < 0 || n >= len(lines) {
  130. return dunno
  131. }
  132. return bytes.TrimSpace(lines[n])
  133. }
  134. // function returns, if possible, the name of the function containing the PC.
  135. func function(pc uintptr) []byte {
  136. fn := runtime.FuncForPC(pc)
  137. if fn == nil {
  138. return dunno
  139. }
  140. name := []byte(fn.Name())
  141. // The name includes the path name to the package, which is unnecessary
  142. // since the file name is already included. Plus, it has center dots.
  143. // That is, we see
  144. // runtime/debug.*T·ptrmethod
  145. // and want
  146. // *T.ptrmethod
  147. // Also the package path might contain dot (e.g. code.google.com/...),
  148. // so first eliminate the path prefix
  149. if lastSlash := bytes.LastIndex(name, slash); lastSlash >= 0 {
  150. name = name[lastSlash+1:]
  151. }
  152. if period := bytes.Index(name, dot); period >= 0 {
  153. name = name[period+1:]
  154. }
  155. name = bytes.ReplaceAll(name, centerDot, dot)
  156. return name
  157. }
  158. // timeFormat returns a customized time string for logger.
  159. func timeFormat(t time.Time) string {
  160. return t.Format("2006/01/02 - 15:04:05")
  161. }