Gin框架

146 阅读3分钟

简介 gin框架是一个典型的http框架;是一个使用的人i比较多的框架,go语言的http框架的设计思路基本都是一样的,学习了gin,以后不管用什么框架,它的思路都是差不多的

gin框架地址

go get -u github.com/gin-gonic/gin 1 快速开始 package main

import ( "github.com/gin-gonic/gin" )

func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080") } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

这段代码不是自己写的,是gin的github上给例子.将代码起来,监听8080端口

访问8080报404,这个是正常的,我们代码是将路由注册在/ping上面

后台日志:

后台会记录相应的日志.

middleware的使用 go.uber.org/zap(日志)

go get -u go.uber.org/zap 1 记录请求路径 package main

import ( "github.com/gin-gonic/gin" "go.uber.org/zap" )

func main() { r := gin.Default() logger, err := zap.NewProduction() if err != nil { panic(err) } r.Use(func(context *gin.Context) { // 在接到请求时开始记录请求路径 logger.Info("incoming request", zap.String("path", context.Request.URL.Path)) // 记录完日志继续执行 context.Next() }) r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.GET("/hello", func(c *gin.Context) { c.String(200, "hello") }) r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080") }

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

记录response code package main

import ( "github.com/gin-gonic/gin" "go.uber.org/zap" )

func main() { r := gin.Default() logger, err := zap.NewProduction() if err != nil { panic(err) } r.Use(func(context *gin.Context) { context.Next() // 在接到请求时开始记录请求路径 logger.Info("incoming request", zap.String("path", context.Request.URL.Path), zap.Int("response code",context.Writer.Status())) }) r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.GET("/hello", func(c *gin.Context) { c.String(200, "hello") }) r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080") }

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 重新进行三次访问,后台日志如下:

记录每次请求耗时 package main

import ( "github.com/gin-gonic/gin" "go.uber.org/zap" "time" )

func main() { r := gin.Default() logger, err := zap.NewProduction() if err != nil { panic(err) } r.Use(func(context *gin.Context) { start := time.Now() context.Next() // 在接到请求时开始记录请求路径 logger.Info("incoming request", zap.String("path", context.Request.URL.Path), zap.Int("response code",context.Writer.Status()), zap.Duration("elapsed",time.Now().Sub(start))) }) r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.GET("/hello", func(c *gin.Context) { c.String(200, "hello") }) r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080") }

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 重新进行三次访问,后台日志如下:

总结

r.Use使用的就是middleware;让所有的请求都从middleware走过.我们可以在每次请求前/后做一些我们想要做的事.这个机制有点类似于JAVA的AOP,但它不是AOP.go语言没那么复杂.AOP那一套过于复杂.通过middleware做到这一点.

Context使用 package main

import ( "github.com/gin-gonic/gin" "go.uber.org/zap" "math/rand" "time" )

const RequestIdKey = "requestId"

func main() { r := gin.Default() logger, err := zap.NewProduction() if err != nil { panic(err) } r.Use(func(context *gin.Context) { start := time.Now() context.Next()

	logger.Info("incoming request", zap.String("path", context.Request.URL.Path),
		zap.Int("response code", context.Writer.Status()),
		zap.Duration("elapsed", time.Now().Sub(start)))
	if requestId, exists := context.Get(RequestIdKey); exists {
		logger.Info("incoming request", zap.Int(RequestIdKey, requestId.(int)))
	}
}, func(context *gin.Context) {
	context.Set(RequestIdKey, rand.Int())
	context.Next()
})
r.GET("/ping", func(c *gin.Context) {
	h := gin.H{
		"message": "pong",
	}
	if requestId, exists := c.Get(RequestIdKey); exists {
		h[RequestIdKey] = requestId
	}
	c.JSON(200, h)
})
r.GET("/hello", func(c *gin.Context) {
	c.String(200, "hello")
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")

}

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

我们在每次请求的时候生成了一个随机的requestId;并返回前端在后台记录! ———————————————— 版权声明:本文为CSDN博主「.番茄炒蛋」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:blog.csdn.net/qq_43135259…