recoverer.go 4.7 KB

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