当前位置:网站首页>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/index
return :
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.560422350
You 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
)
边栏推荐
- Students who do not understand the code can also send their own token, which is easy to learn BSC
- JSON serialization case summary
- Open PHP error prompt under Ubuntu 14.04
- Mycms we media mall v3.4.1 release, user manual update
- [技术发展-24]:现有物联网通信技术特点
- SQL Injection (GET/Search)
- JS convert pseudo array to array
- Which securities company has the lowest Commission for opening an account online? I want to open an account. Is it safe for the online account manager to open an account
- 挡不住了,国产芯片再度突进,部分环节已进到4nm
- 【BW16 应用篇】安信可BW16模组与开发板更新固件烧录说明
猜你喜欢
[redis] cache warm-up, cache avalanche and cache breakdown
太阳底下无新事,元宇宙能否更上层楼?
Flutter动态化 | Fair 2.5.0 新版本特性
Go language unit test 4: go language uses gomonkey to test functions or methods
Ocean CMS vulnerability - search php
Flutter dynamic | fair 2.5.0 new version features
Typeerror resolved: argument 'parser' has incorrect type (expected lxml.etree.\u baseparser, got type)
Universal dividend source code, supports the dividend of any B on the BSC
HALCON联合C#检测表面缺陷——HALCON例程autobahn
3D视觉——2.人体姿态估计(Pose Estimation)入门——OpenPose含安装、编译、使用(单帧、实时视频)
随机推荐
php 迷宫游戏
Software testing is so hard to find, only outsourcing offers, should I go?
Kivy tutorial how to automatically load kV files
PHP maze game
Flutter dynamic | fair 2.5.0 new version features
Leetcode-1175.Prime Arrangements
mysql更新时条件为一查询
Box layout of Kivy tutorial BoxLayout arranges sub items in vertical or horizontal boxes (tutorial includes source code)
MyCms 自媒体商城 v3.4.1 发布,使用手册更新
Internet of things completion -- (stm32f407 connects to cloud platform detection data)
Comprehensively develop the main channel of digital economy and digital group, and actively promote the utonmos digital Tibet market
Complete DNN deep neural network CNN training with tensorflow to complete image recognition cases
CVPR 2022 | 美团技术团队精选6篇优秀论文解读
Halcon combined with C # to detect surface defects -- Halcon routine autobahn
Kivy教程之 如何通过字符串方式载入kv文件设计界面(教程含源码)
Several common optimization methods matlab principle and depth analysis
【556. 下一个更大元素 III】
Bidirectional linked list (we only need to pay attention to insert and delete functions)
MySQL 数据处理值增删改
[sort] bucket sort