You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

recoverer.go 4.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. package middleware
  2. // The original work was derived from Goji's middleware, source:
  3. // https://github.com/zenazn/goji/tree/master/web/middleware
  4. import (
  5. "bytes"
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "os"
  10. "runtime/debug"
  11. "strings"
  12. )
  13. // Recoverer is a middleware that recovers from panics, logs the panic (and a
  14. // backtrace), and returns a HTTP 500 (Internal Server Error) status if
  15. // possible. Recoverer prints a request ID if one is provided.
  16. //
  17. // Alternatively, look at https://github.com/pressly/lg middleware pkgs.
  18. func Recoverer(next http.Handler) http.Handler {
  19. fn := func(w http.ResponseWriter, r *http.Request) {
  20. defer func() {
  21. if rvr := recover(); rvr != nil && rvr != http.ErrAbortHandler {
  22. logEntry := GetLogEntry(r)
  23. if logEntry != nil {
  24. logEntry.Panic(rvr, debug.Stack())
  25. } else {
  26. PrintPrettyStack(rvr)
  27. }
  28. w.WriteHeader(http.StatusInternalServerError)
  29. }
  30. }()
  31. next.ServeHTTP(w, r)
  32. }
  33. return http.HandlerFunc(fn)
  34. }
  35. func PrintPrettyStack(rvr interface{}) {
  36. debugStack := debug.Stack()
  37. s := prettyStack{}
  38. out, err := s.parse(debugStack, rvr)
  39. if err == nil {
  40. os.Stderr.Write(out)
  41. } else {
  42. // print stdlib output as a fallback
  43. os.Stderr.Write(debugStack)
  44. }
  45. }
  46. type prettyStack struct {
  47. }
  48. func (s prettyStack) parse(debugStack []byte, rvr interface{}) ([]byte, error) {
  49. var err error
  50. useColor := true
  51. buf := &bytes.Buffer{}
  52. cW(buf, false, bRed, "\n")
  53. cW(buf, useColor, bCyan, " panic: ")
  54. cW(buf, useColor, bBlue, "%v", rvr)
  55. cW(buf, false, bWhite, "\n \n")
  56. // process debug stack info
  57. stack := strings.Split(string(debugStack), "\n")
  58. lines := []string{}
  59. // locate panic line, as we may have nested panics
  60. for i := len(stack) - 1; i > 0; i-- {
  61. lines = append(lines, stack[i])
  62. if strings.HasPrefix(stack[i], "panic(0x") {
  63. lines = lines[0 : len(lines)-2] // remove boilerplate
  64. break
  65. }
  66. }
  67. // reverse
  68. for i := len(lines)/2 - 1; i >= 0; i-- {
  69. opp := len(lines) - 1 - i
  70. lines[i], lines[opp] = lines[opp], lines[i]
  71. }
  72. // decorate
  73. for i, line := range lines {
  74. lines[i], err = s.decorateLine(line, useColor, i)
  75. if err != nil {
  76. return nil, err
  77. }
  78. }
  79. for _, l := range lines {
  80. fmt.Fprintf(buf, "%s", l)
  81. }
  82. return buf.Bytes(), nil
  83. }
  84. func (s prettyStack) decorateLine(line string, useColor bool, num int) (string, error) {
  85. line = strings.TrimSpace(line)
  86. if strings.HasPrefix(line, "\t") || strings.Contains(line, ".go:") {
  87. return s.decorateSourceLine(line, useColor, num)
  88. } else if strings.HasSuffix(line, ")") {
  89. return s.decorateFuncCallLine(line, useColor, num)
  90. } else {
  91. if strings.HasPrefix(line, "\t") {
  92. return strings.Replace(line, "\t", " ", 1), nil
  93. } else {
  94. return fmt.Sprintf(" %s\n", line), nil
  95. }
  96. }
  97. }
  98. func (s prettyStack) decorateFuncCallLine(line string, useColor bool, num int) (string, error) {
  99. idx := strings.LastIndex(line, "(")
  100. if idx < 0 {
  101. return "", errors.New("not a func call line")
  102. }
  103. buf := &bytes.Buffer{}
  104. pkg := line[0:idx]
  105. // addr := line[idx:]
  106. method := ""
  107. if idx := strings.LastIndex(pkg, string(os.PathSeparator)); idx < 0 {
  108. if idx := strings.Index(pkg, "."); idx > 0 {
  109. method = pkg[idx:]
  110. pkg = pkg[0:idx]
  111. }
  112. } else {
  113. method = pkg[idx+1:]
  114. pkg = pkg[0 : idx+1]
  115. if idx := strings.Index(method, "."); idx > 0 {
  116. pkg += method[0:idx]
  117. method = method[idx:]
  118. }
  119. }
  120. pkgColor := nYellow
  121. methodColor := bGreen
  122. if num == 0 {
  123. cW(buf, useColor, bRed, " -> ")
  124. pkgColor = bMagenta
  125. methodColor = bRed
  126. } else {
  127. cW(buf, useColor, bWhite, " ")
  128. }
  129. cW(buf, useColor, pkgColor, "%s", pkg)
  130. cW(buf, useColor, methodColor, "%s\n", method)
  131. // cW(buf, useColor, nBlack, "%s", addr)
  132. return buf.String(), nil
  133. }
  134. func (s prettyStack) decorateSourceLine(line string, useColor bool, num int) (string, error) {
  135. idx := strings.LastIndex(line, ".go:")
  136. if idx < 0 {
  137. return "", errors.New("not a source line")
  138. }
  139. buf := &bytes.Buffer{}
  140. path := line[0 : idx+3]
  141. lineno := line[idx+3:]
  142. idx = strings.LastIndex(path, string(os.PathSeparator))
  143. dir := path[0 : idx+1]
  144. file := path[idx+1:]
  145. idx = strings.Index(lineno, " ")
  146. if idx > 0 {
  147. lineno = lineno[0:idx]
  148. }
  149. fileColor := bCyan
  150. lineColor := bGreen
  151. if num == 1 {
  152. cW(buf, useColor, bRed, " -> ")
  153. fileColor = bRed
  154. lineColor = bMagenta
  155. } else {
  156. cW(buf, false, bWhite, " ")
  157. }
  158. cW(buf, useColor, bWhite, "%s", dir)
  159. cW(buf, useColor, fileColor, "%s", file)
  160. cW(buf, useColor, lineColor, "%s", lineno)
  161. if num == 1 {
  162. cW(buf, false, bWhite, "\n")
  163. }
  164. cW(buf, false, bWhite, "\n")
  165. return buf.String(), nil
  166. }