recovery.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. "fmt"
  8. "io"
  9. "io/ioutil"
  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 interface{})
  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. if se, ok := ne.Err.(*os.SyscallError); ok {
  56. if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
  57. brokenPipe = true
  58. }
  59. }
  60. }
  61. if logger != nil {
  62. stack := stack(3)
  63. httpRequest, _ := httputil.DumpRequest(c.Request, false)
  64. headers := strings.Split(string(httpRequest), "\r\n")
  65. for idx, header := range headers {
  66. current := strings.Split(header, ":")
  67. if current[0] == "Authorization" {
  68. headers[idx] = current[0] + ": *"
  69. }
  70. }
  71. headersToStr := strings.Join(headers, "\r\n")
  72. if brokenPipe {
  73. logger.Printf("%s\n%s%s", err, headersToStr, reset)
  74. } else if IsDebugging() {
  75. logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s",
  76. timeFormat(time.Now()), headersToStr, err, stack, reset)
  77. } else {
  78. logger.Printf("[Recovery] %s panic recovered:\n%s\n%s%s",
  79. timeFormat(time.Now()), err, stack, reset)
  80. }
  81. }
  82. if brokenPipe {
  83. // If the connection is dead, we can't write a status to it.
  84. c.Error(err.(error)) // nolint: errcheck
  85. c.Abort()
  86. } else {
  87. handle(c, err)
  88. }
  89. }
  90. }()
  91. c.Next()
  92. }
  93. }
  94. func defaultHandleRecovery(c *Context, err interface{}) {
  95. c.AbortWithStatus(http.StatusInternalServerError)
  96. }
  97. // stack returns a nicely formatted stack frame, skipping skip frames.
  98. func stack(skip int) []byte {
  99. buf := new(bytes.Buffer) // the returned data
  100. // As we loop, we open files and read them. These variables record the currently
  101. // loaded file.
  102. var lines [][]byte
  103. var lastFile string
  104. for i := skip; ; i++ { // Skip the expected number of frames
  105. pc, file, line, ok := runtime.Caller(i)
  106. if !ok {
  107. break
  108. }
  109. // Print this much at least. If we can't find the source, it won't show.
  110. fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
  111. if file != lastFile {
  112. data, err := ioutil.ReadFile(file)
  113. if err != nil {
  114. continue
  115. }
  116. lines = bytes.Split(data, []byte{'\n'})
  117. lastFile = file
  118. }
  119. fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line))
  120. }
  121. return buf.Bytes()
  122. }
  123. // source returns a space-trimmed slice of the n'th line.
  124. func source(lines [][]byte, n int) []byte {
  125. n-- // in stack trace, lines are 1-indexed but our array is 0-indexed
  126. if n < 0 || n >= len(lines) {
  127. return dunno
  128. }
  129. return bytes.TrimSpace(lines[n])
  130. }
  131. // function returns, if possible, the name of the function containing the PC.
  132. func function(pc uintptr) []byte {
  133. fn := runtime.FuncForPC(pc)
  134. if fn == nil {
  135. return dunno
  136. }
  137. name := []byte(fn.Name())
  138. // The name includes the path name to the package, which is unnecessary
  139. // since the file name is already included. Plus, it has center dots.
  140. // That is, we see
  141. // runtime/debug.*T·ptrmethod
  142. // and want
  143. // *T.ptrmethod
  144. // Also the package path might contains dot (e.g. code.google.com/...),
  145. // so first eliminate the path prefix
  146. if lastSlash := bytes.LastIndex(name, slash); lastSlash >= 0 {
  147. name = name[lastSlash+1:]
  148. }
  149. if period := bytes.Index(name, dot); period >= 0 {
  150. name = name[period+1:]
  151. }
  152. name = bytes.Replace(name, centerDot, dot, -1)
  153. return name
  154. }
  155. func timeFormat(t time.Time) string {
  156. timeString := t.Format("2006/01/02 - 15:04:05")
  157. return timeString
  158. }