栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

gin框架

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

gin框架

简介

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

gin框架地址

go get -u github.com/gin-gonic/gin
快速开始
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")
}


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

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

后台日志:

后台会记录相应的日志.

middleware的使用

go.uber.org/zap(日志)

go get -u go.uber.org/zap
记录请求路径
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")
}




记录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")
}

重新进行三次访问,后台日志如下:

记录每次请求耗时
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")
}

重新进行三次访问,后台日志如下:

总结


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")
}



我们在每次请求的时候生成了一个随机的requestId;并返回前端在后台记录!

笔者刚开始学习go语言,代码有些地方不是很规范.能力一般;水平有限,有些地方可能理解错了或理解不到位的,请大家多多指出!Thanks

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/902712.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号