-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
50 lines (47 loc) · 1.15 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
50
package telescope
import (
"bytes"
"fmt"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
"runtime/debug"
"time"
)
// Telescope 启用望眼镜
func Telescope() gin.HandlerFunc {
return func(ctx *gin.Context) {
defer func() {
if r := recover(); r != nil {
log.WithField("url", ctx.Request.URL.Path).Error(fmt.Sprint(r) + "\n" + string(debug.Stack()))
ctx.JSON(http.StatusInternalServerError, gin.H{
"code": 1,
"message": "服务器内部错误",
})
ctx.Abort()
}
if errorRecord && hasError {
log.WithContext(ctx).WithFields(log.Fields{"type": "request"}).Error(ctx.Request.URL)
defer func() {
hasError = false
}()
} else {
log.WithContext(ctx).WithFields(log.Fields{"type": "request"}).Debug(ctx.Request.URL)
}
TelescopeClose()
}()
ctx.Set("start", time.Now())
TelescopeStart()
ctx.Writer = &TelescopeResponseWriter{
Body: bytes.NewBufferString(""),
ResponseWriter: ctx.Writer,
}
data, err := ctx.GetRawData()
if err == nil {
ctx.Set("raw", data)
ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(data))
}
ctx.Next()
}
}