当前位置:网站首页>Go language web development series 26: Gin framework: demonstrates the execution sequence of code when there are multiple middleware
Go language web development series 26: Gin framework: demonstrates the execution sequence of code when there are multiple middleware
2022-07-03 13:47:00 【Lao Liu, you are so awesome】
One , Libraries required for installation
1,gin In the framework of github The address of :
https://github.com/gin-gonic/gin
2, Install... From the command line :
[email protected]:/data/go/ginhello# go get -u github.com/gin-gonic/[email protected] explain : Liu Hongdi's go The forest is a focus golang The blog of ,
Address :https://blog.csdn.net/weixin_43881017
explain : author : Liu Hongdi mailbox : [email protected]
Two , Information about the demonstration project
1, Project address :
https://github.com/liuhongdi/digv26
2, Functional specifications : Demonstrate using multiple middleware( middleware ) when ,middleware The execution order of the code in
3, Project structure : Pictured :

3、 ... and ,go Code instructions
1,middleware/middle.go
package middleware
import (
"fmt"
"github.com/gin-gonic/gin"
"time"
)
// first middleware
func MiddlewareOne() gin.HandlerFunc {
return func(c *gin.Context) {
fmt.Println("before middlewareOne: "+time.Now().String())
c.Next()
fmt.Println("after middlewareOne: "+time.Now().String())
return
}
}
// the second middleware
func MiddlewareTwo() gin.HandlerFunc {
return func(c *gin.Context) {
fmt.Println("before middlewareTwo: "+time.Now().String())
c.Next()
fmt.Println("after middlewareTwo: "+time.Now().String())
return
}
}
// Third middleware
func MiddlewareThree() gin.HandlerFunc {
return func(c *gin.Context) {
fmt.Println("before MiddlewareThree: "+time.Now().String())
c.Next()
fmt.Println("after MiddlewareThree: "+time.Now().String())
return
}
}2,router/router.go
package router
import (
"github.com/gin-gonic/gin"
"github.com/liuhongdi/digv26/controller"
"github.com/liuhongdi/digv26/global"
"github.com/liuhongdi/digv26/middleware"
"log"
"runtime/debug"
)
func Router() *gin.Engine {
router := gin.Default()
// Handling exceptions
router.NoRoute(HandleNotFound)
router.NoMethod(HandleNotFound)
//use middleware
router.Use(middleware.MiddlewareTwo())
router.Use(middleware.MiddlewareOne())
router.Use(middleware.MiddlewareThree())
router.Use(Recover)
// Path mapping :index
indexc:=controller.NewIndexController()
router.GET("/index/index", indexc.Index);
return router
}
func HandleNotFound(c *gin.Context) {
global.NewResult(c).Error(404," Resource not found ")
return
}
func Recover(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
// Print error stack information
log.Printf("panic: %v\n", r)
debug.PrintStack()
global.NewResult(c).Error(500," Server internal error ")
}
}()
// Finished loading defer recover, Continue with subsequent interface calls
c.Next()
}3,controller/indexController.go
package controller
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/liuhongdi/digv26/global"
"time"
)
type IndexController struct{}
func NewIndexController() IndexController {
return IndexController{}
}
// Return a successful prompt
func (g *IndexController) Index(c *gin.Context) {
fmt.Println("controller:index: "+time.Now().String())
result := global.NewResult(c)
result.Success("success");
return
}
Four , The test results
visit :
http://127.0.0.1:8080/index/indexreturn :

Look at the output of the console :
before middlewareTwo: 2021-02-03 11:52:29.84260954 +0800 CST m=+3.560203369
before middlewareOne: 2021-02-03 11:52:29.842749172 +0800 CST m=+3.560342999
before MiddlewareThree: 2021-02-03 11:52:29.842758214 +0800 CST m=+3.560352049
controller:index: 2021-02-03 11:52:29.842761431 +0800 CST m=+3.560355255
after MiddlewareThree: 2021-02-03 11:52:29.842819585 +0800 CST m=+3.560413419
after middlewareOne: 2021-02-03 11:52:29.842825746 +0800 CST m=+3.560419571
after middlewareTwo: 2021-02-03 11:52:29.842828523 +0800 CST m=+3.560422350You can see :
There are many. middleware when
about next Previous code , Is in accordance with the use The order of takes effect ,
and next Later code , It takes effect in the reverse order
5、 ... and , View the version of the library :
module github.com/liuhongdi/digv26
go 1.15
require (
github.com/gin-gonic/gin v1.6.3
)
边栏推荐
- Libuv Library - Design Overview (Chinese version)
- Replace the GPU card number when pytorch loads the historical model, map_ Location settings
- Box layout of Kivy tutorial BoxLayout arranges sub items in vertical or horizontal boxes (tutorial includes source code)
- Flutter dynamic | fair 2.5.0 new version features
- Shell timing script, starting from 0, CSV format data is regularly imported into PostgreSQL database shell script example
- The solution of Chinese font garbled code in keil5
- PowerPoint 教程,如何在 PowerPoint 中將演示文稿另存為視頻?
- 树的深入和广度优先遍历(不考虑二叉树)
- 太阳底下无新事,元宇宙能否更上层楼?
- [how to earn a million passive income]
猜你喜欢
![[技術發展-24]:現有物聯網通信技術特點](/img/f3/a219fe8e7438b8974d2226b4c3d4a4.png)
[技術發展-24]:現有物聯網通信技術特點

Several common optimization methods matlab principle and depth analysis
![[quantitative trading] permanent portfolio, turtle trading rules reading, back testing and discussion](/img/3b/28327bbf5eb19254f03500a41e2adb.jpg)
[quantitative trading] permanent portfolio, turtle trading rules reading, back testing and discussion

AI 考高数得分 81,网友:AI 模型也免不了“内卷”!

Bidirectional linked list (we only need to pay attention to insert and delete functions)
![[technology development-24]: characteristics of existing IOT communication technology](/img/f3/a219fe8e7438b8974d2226b4c3d4a4.png)
[technology development-24]: characteristics of existing IOT communication technology

TensorBoard可视化处理案例简析

PhpMyAdmin stage file contains analysis traceability

There is nothing new under the sun. Can the meta universe go higher?

Kivy tutorial how to automatically load kV files
随机推荐
[技术发展-24]:现有物联网通信技术特点
mysql中的字段问题
PowerPoint 教程,如何在 PowerPoint 中將演示文稿另存為視頻?
Road construction issues
Error running 'application' in idea running: the solution of command line is too long
Swiftui development experience: the five most powerful principles that a programmer needs to master
Asp.Net Core1.1版本没了project.json,这样来生成跨平台包
R language uses the data function to obtain the sample datasets available in the current R environment: obtain all the sample datasets in the datasets package, obtain the datasets of all packages, and
Windos creates Cordova prompt because running scripts is prohibited on this system
软件测试工作那么难找,只有外包offer,我该去么?
CVPR 2022 | 美团技术团队精选6篇优秀论文解读
常见的几种最优化方法Matlab原理和深度分析
Internet of things completion -- (stm32f407 connects to cloud platform detection data)
Multi table query of MySQL - multi table relationship and related exercises
Go language unit test 3: go language uses gocovey library to do unit test
【电脑插入U盘或者内存卡显示无法格式化FAT32如何解决】
JVM系列——概述,程序计数器day1-1
Kivy tutorial how to load kV file design interface by string (tutorial includes source code)
Kivy教程之 如何自动载入kv文件
The principle of human voice transformer