-
Notifications
You must be signed in to change notification settings - Fork 0
/
recovery_middleware.go
72 lines (66 loc) · 1.39 KB
/
recovery_middleware.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package tgin
import (
"bytes"
"fmt"
"log"
"net"
"os"
"runtime"
"strings"
)
var (
dunno = []byte("???")
cdot = []byte("·")
dot = []byte(".")
slash = []byte("/")
)
func RecoveryMiddleware(c *Context) {
defer handlePanic(c)
c.Next()
}
func handlePanic(c *Context) {
if err := recover(); err != nil {
brokenPipe := false
if ne, ok := err.(*net.OpError); ok {
if se, ok := ne.Err.(*os.SyscallError); ok {
if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
brokenPipe = true
}
}
}
stack := dumpStack(3)
log.Printf("[Recovery] panic recovered: %s\n%s\n", err, stack)
if brokenPipe {
c.Abort()
} else {
c.AbortWithStatus(500)
}
}
}
func dumpStack(skip int) []byte {
buf := bytes.NewBuffer(nil)
for i := skip; ; i++ {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
fmt.Fprintf(buf, "\tfunc: %s\n", function(pc))
}
return buf.Bytes()
}
func function(pc uintptr) []byte {
fn := runtime.FuncForPC(pc)
if fn == nil {
return dunno
}
name := []byte(fn.Name())
if lastSlash := bytes.LastIndex(name, slash); lastSlash >= 0 {
name = name[lastSlash+1:]
}
if period := bytes.Index(name, dot); period >= 0 {
name = name[period+1:]
}
name = bytes.Replace(name, cdot, dot, -1)
return name
}