recovery.go 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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/http/httputil"
  12. "runtime"
  13. )
  14. var (
  15. dunno = []byte("???")
  16. centerDot = []byte("·")
  17. dot = []byte(".")
  18. slash = []byte("/")
  19. )
  20. // Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
  21. func Recovery() HandlerFunc {
  22. return RecoveryWithWriter(DefaultErrorWriter)
  23. }
  24. func RecoveryWithWriter(out io.Writer) HandlerFunc {
  25. var logger *log.Logger
  26. if out != nil {
  27. logger = log.New(out, "\n\n\x1b[31m", log.LstdFlags)
  28. }
  29. return func(c *Context) {
  30. defer func() {
  31. if err := recover(); err != nil {
  32. if logger != nil {
  33. stack := stack(3)
  34. httprequest, _ := httputil.DumpRequest(c.Request, false)
  35. logger.Printf("[Recovery] panic recovered:\n%s\n%s\n%s%s", string(httprequest), err, stack, reset)
  36. }
  37. c.AbortWithStatus(500)
  38. }
  39. }()
  40. c.Next()
  41. }
  42. }
  43. // stack returns a nicely formated stack frame, skipping skip frames
  44. func stack(skip int) []byte {
  45. buf := new(bytes.Buffer) // the returned data
  46. // As we loop, we open files and read them. These variables record the currently
  47. // loaded file.
  48. var lines [][]byte
  49. var lastFile string
  50. for i := skip; ; i++ { // Skip the expected number of frames
  51. pc, file, line, ok := runtime.Caller(i)
  52. if !ok {
  53. break
  54. }
  55. // Print this much at least. If we can't find the source, it won't show.
  56. fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
  57. if file != lastFile {
  58. data, err := ioutil.ReadFile(file)
  59. if err != nil {
  60. continue
  61. }
  62. lines = bytes.Split(data, []byte{'\n'})
  63. lastFile = file
  64. }
  65. fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line))
  66. }
  67. return buf.Bytes()
  68. }
  69. // source returns a space-trimmed slice of the n'th line.
  70. func source(lines [][]byte, n int) []byte {
  71. n-- // in stack trace, lines are 1-indexed but our array is 0-indexed
  72. if n < 0 || n >= len(lines) {
  73. return dunno
  74. }
  75. return bytes.TrimSpace(lines[n])
  76. }
  77. // function returns, if possible, the name of the function containing the PC.
  78. func function(pc uintptr) []byte {
  79. fn := runtime.FuncForPC(pc)
  80. if fn == nil {
  81. return dunno
  82. }
  83. name := []byte(fn.Name())
  84. // The name includes the path name to the package, which is unnecessary
  85. // since the file name is already included. Plus, it has center dots.
  86. // That is, we see
  87. // runtime/debug.*T·ptrmethod
  88. // and want
  89. // *T.ptrmethod
  90. // Also the package path might contains dot (e.g. code.google.com/...),
  91. // so first eliminate the path prefix
  92. if lastslash := bytes.LastIndex(name, slash); lastslash >= 0 {
  93. name = name[lastslash+1:]
  94. }
  95. if period := bytes.Index(name, dot); period >= 0 {
  96. name = name[period+1:]
  97. }
  98. name = bytes.Replace(name, centerDot, dot, -1)
  99. return name
  100. }