recovery.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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. // Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
  26. func Recovery() HandlerFunc {
  27. return RecoveryWithWriter(DefaultErrorWriter)
  28. }
  29. // RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.
  30. func RecoveryWithWriter(out io.Writer) HandlerFunc {
  31. var logger *log.Logger
  32. if out != nil {
  33. logger = log.New(out, "\n\n\x1b[31m", log.LstdFlags)
  34. }
  35. return func(c *Context) {
  36. defer func() {
  37. if err := recover(); err != nil {
  38. // Check for a broken connection, as it is not really a
  39. // condition that warrants a panic stack trace.
  40. var brokenPipe bool
  41. if ne, ok := err.(*net.OpError); ok {
  42. if se, ok := ne.Err.(*os.SyscallError); ok {
  43. if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
  44. brokenPipe = true
  45. }
  46. }
  47. }
  48. if logger != nil {
  49. stack := stack(3)
  50. httprequest, _ := httputil.DumpRequest(c.Request, false)
  51. if brokenPipe {
  52. logger.Printf("%s\n%s%s", err, string(httprequest), reset)
  53. } else if IsDebugging() {
  54. logger.Printf("[Recovery] %s panic recovered:\n%s\n%s\n%s%s",
  55. timeFormat(time.Now()), string(httprequest), err, stack, reset)
  56. } else {
  57. logger.Printf("[Recovery] %s panic recovered:\n%s\n%s%s",
  58. timeFormat(time.Now()), err, stack, reset)
  59. }
  60. }
  61. // If the connection is dead, we can't write a status to it.
  62. if brokenPipe {
  63. c.Error(err.(error)) // nolint: errcheck
  64. c.Abort()
  65. } else {
  66. c.AbortWithStatus(http.StatusInternalServerError)
  67. }
  68. }
  69. }()
  70. c.Next()
  71. }
  72. }
  73. // stack returns a nicely formatted stack frame, skipping skip frames.
  74. func stack(skip int) []byte {
  75. buf := new(bytes.Buffer) // the returned data
  76. // As we loop, we open files and read them. These variables record the currently
  77. // loaded file.
  78. var lines [][]byte
  79. var lastFile string
  80. for i := skip; ; i++ { // Skip the expected number of frames
  81. pc, file, line, ok := runtime.Caller(i)
  82. if !ok {
  83. break
  84. }
  85. // Print this much at least. If we can't find the source, it won't show.
  86. fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
  87. if file != lastFile {
  88. data, err := ioutil.ReadFile(file)
  89. if err != nil {
  90. continue
  91. }
  92. lines = bytes.Split(data, []byte{'\n'})
  93. lastFile = file
  94. }
  95. fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line))
  96. }
  97. return buf.Bytes()
  98. }
  99. // source returns a space-trimmed slice of the n'th line.
  100. func source(lines [][]byte, n int) []byte {
  101. n-- // in stack trace, lines are 1-indexed but our array is 0-indexed
  102. if n < 0 || n >= len(lines) {
  103. return dunno
  104. }
  105. return bytes.TrimSpace(lines[n])
  106. }
  107. // function returns, if possible, the name of the function containing the PC.
  108. func function(pc uintptr) []byte {
  109. fn := runtime.FuncForPC(pc)
  110. if fn == nil {
  111. return dunno
  112. }
  113. name := []byte(fn.Name())
  114. // The name includes the path name to the package, which is unnecessary
  115. // since the file name is already included. Plus, it has center dots.
  116. // That is, we see
  117. // runtime/debug.*T·ptrmethod
  118. // and want
  119. // *T.ptrmethod
  120. // Also the package path might contains dot (e.g. code.google.com/...),
  121. // so first eliminate the path prefix
  122. if lastslash := bytes.LastIndex(name, slash); lastslash >= 0 {
  123. name = name[lastslash+1:]
  124. }
  125. if period := bytes.Index(name, dot); period >= 0 {
  126. name = name[period+1:]
  127. }
  128. name = bytes.Replace(name, centerDot, dot, -1)
  129. return name
  130. }
  131. func timeFormat(t time.Time) string {
  132. var timeString = t.Format("2006/01/02 - 15:04:05")
  133. return timeString
  134. }