GIN 中间件

1. 日志打印

需要的引入的包:

将日志按天分隔

  • github.com/lestrrat-go/file-rotatelogs”

  • github.com/rifflock/lfshook

go里面一个用的比较多的日志框架

  • github.com/sirupsen/logrus

整个代码:

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
73
74
75
76
77

func Logger() gin.HandlerFunc {
filePath := "PsBlog/log/log"
src , err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0755)
if err!=nil{
fmt.Println("err :", err)
}
logger := logrus.New()

logger.Out = src

logger.SetLevel(logrus.DebugLevel)

logWriter , _ := rotate.New(
filePath+"%Y%m%d.log",
rotate.WithMaxAge(7*24*time.Hour),
rotate.WithRotationTime(24*time.Hour),
)

writeMap := lfshook.WriterMap{
logrus.InfoLevel: logWriter,
logrus.FatalLevel: logWriter,
logrus.DebugLevel: logWriter,
logrus.WarnLevel: logWriter,
logrus.ErrorLevel: logWriter,
logrus.PanicLevel: logWriter,
}

Hook := lfshook.NewHook(writeMap, &logrus.TextFormatter{
// 123456
TimestampFormat: "2006-01-02 15:04:05",
})
logger.AddHook(Hook)

return func(c *gin.Context) {
startTime := time.Now()
// 执行之后的中间件,logger中间件最后反过头执行
stopTime := time.Since(startTime)
spendTime := fmt.Sprintf("%d ms", int(math.Ceil(float64(stopTime.Nanoseconds()/100000.0))))
hostName, err := os.Hostname()
if err != nil{
hostName = "unknown"
}
statusCode := c.Writer.Status()
clientIP := c.ClientIP()
userAgent := c.Request.UserAgent()
dataSize := c.Writer.Size()

method := c.Request.Method
path := c.Request.RequestURI

entry := logger.WithFields(logrus.Fields{
"HoseName" : hostName,
"status" : statusCode,
"SpendTime" : spendTime,
"IP" : clientIP,
"Method" : method,
"Path" : path,
"DataSize" : dataSize,
"Agent" : userAgent,
})

if len(c.Errors) > 0{
entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())
}

if statusCode >= 500{
entry.Error()
}else if statusCode >= 400{
entry.Warn()
}else {
entry.Info()
}

}
}

2. 跨域请求

需要用到的包

  • github.com/gin-contrib/cors

整个代码(比较简单的初级配置):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//跨域配置
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
cors.New(cors.Config{
//AllowOrigins: []string{"https://foo.com"},
AllowMethods: []string{"*"},
AllowHeaders: []string{"Origin"},
ExposeHeaders: []string{"Content-Length", "Authorization"},
//cookie 本身不能跨域
//AllowCredentials: true,
//AllowOriginFunc: func(origin string) bool {
// return origin == "https://github.com"
//},
MaxAge: 12 * time.Hour,
})
}
}