forked from Terry-Mao/goim
/
middleware.go
49 lines (43 loc) · 1.11 KB
/
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
package http
import (
"fmt"
"net/http/httputil"
"runtime"
"time"
"github.com/gin-gonic/gin"
log "github.com/golang/glog"
)
func loggerHandler(c *gin.Context) {
// Start timer
start := time.Now()
path := c.Request.URL.Path
raw := c.Request.URL.RawQuery
method := c.Request.Method
// Process request
c.Next()
// Stop timer
end := time.Now()
latency := end.Sub(start)
statusCode := c.Writer.Status()
ecode := c.GetInt(contextErrCode)
clientIP := c.ClientIP()
if raw != "" {
path = path + "?" + raw
}
log.Infof("METHOD:%s | PATH:%s | CODE:%d | IP:%s | TIME:%d | ECODE:%d", method, path, statusCode, clientIP, latency/time.Millisecond, ecode)
}
func recoverHandler(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
httprequest, _ := httputil.DumpRequest(c.Request, false)
pnc := fmt.Sprintf("[Recovery] %s panic recovered:\n%s\n%s\n%s", time.Now().Format("2006-01-02 15:04:05"), string(httprequest), err, buf)
fmt.Print(pnc)
log.Error(pnc)
c.AbortWithStatus(500)
}
}()
c.Next()
}