recovery.go 3.0 KB

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