recovery.go 2.8 KB

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