当前位置:网站首页>11. Gin Middleware
11. Gin Middleware
2022-07-21 00:29:00 【Endless character】
Catalog
Preface
- Suppose a scenario , We need to count the call duration of each function ; If we record the time at the beginning of each function , Calculate the elapsed time at the end , This is very unusual , And the code is very intrusive
- At this time, the middleware solution can be used to solve the above problems
One 、 Use of middleware
- router := gin.Default(): By default gin Of Logger and Recovery Middleware
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
router := gin.New()
// Use logger、recovery middleware , Global all
router.Use(gin.Logger(), gin.Recovery())
// middleware AuthRequired Only a call "/goods" At the beginning URL It works
authrized := router.Group("/goods")
authrized.Use(AuthRequired)
router.Run(":8088")
}
func AuthRequired(context *gin.Context) {
}
Two 、 Custom middleware
- Demand fulfillment : Use custom middleware , Count the time consumption of each request
package main
import (
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
func MyLogger() gin.HandlerFunc {
return func(c *gin.Context) {
t := time.Now()
c.Set("example", "123456")
// Let the original logic continue
c.Next()
end := time.Since(t)
fmt.Printf(" Time consuming :%v\n", end)
status := c.Writer.Status()
fmt.Println(" state ", status)
}
}
func main() {
router := gin.Default()
router.Use(MyLogger())
router.GET("/ping", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
router.Run(":8088")
}
3、 ... and 、 Terminate the subsequent logic execution of the middleware
- Use in middleware Abort To prevent the execution of subsequent logic : Out of commission return To execute
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func TokenRequired() gin.HandlerFunc {
return func(c *gin.Context) {
var token string
for k, v := range c.Request.Header {
if k == "x-Token" {
// Be sure to use capitalization here
token = v[0]
}
fmt.Println(k, v)
}
if token != "test" {
c.JSON(http.StatusUnauthorized, gin.H{
"msg": " Not logged in ",
})
// return
c.Abort() // If you want to skip the original execution logic , Out of commission return
}
c.Next()
}
}
func main() {
router := gin.Default()
router.Use(TokenRequired())
router.GET("/ping", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
router.Run(":8088")
}
Four 、gin return html
1 - Use gin return html
- Official address :https://golang.org/pkg/html/template
package main
import (
"fmt"
"net/http"
"os"
"path/filepath"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
fmt.Println("path -> ", dir)
// LoadHTMLFiles The files in the specified directory will be loaded , Relative catalog
router.LoadHTMLFiles("templates/index.tmpl")
router.GET("/index", func(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": " Study ",
})
})
router.Run(":8088")
}
- index.tmpl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>
{
{ .title }}
</h1>
</body>
</html>
2 - Load multiple html file
package main
import (
"fmt"
"net/http"
"os"
"path/filepath"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
fmt.Println("path -> ", dir)
// LoadHTMLFiles The files in the specified directory will be loaded , Relative catalog
//router.LoadHTMLFiles("templates/index.tmpl", "templates/goods.html")
// If there are too many files , It also needs to be 1 Writing is too complicated , This directly loads all the files in the corresponding directory
router.LoadHTMLGlob("templates/*")
router.GET("/index", func(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": " Study ",
})
})
router.GET("/goods", func(c *gin.Context) {
c.HTML(http.StatusOK, "goods.html", gin.H{
"name": " Microservice development ",
})
})
router.Run(":8088")
}
- goods.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>
{
{ .name }}
</h1>
</body>
</html>
3 - File conflict with the same name
- Problem introduction : If there are files with the same name under different folders , How to resolve conflicts
- stay html Join at the beginning :{ {define “users/list.html”}}
- stay html Add... At the end :{ {end}}
If not used in the template define Definition Then we can use the default file name to find
- main.go
package main
import (
"fmt"
"net/http"
"os"
"path/filepath"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
fmt.Println("path -> ", dir)
// LoadHTMLFiles The files in the specified directory will be loaded , Relative catalog
router.LoadHTMLGlob("templates/**/*")
router.GET("/goods/list", func(c *gin.Context) {
c.HTML(http.StatusOK, "goods/list.html", gin.H{
"title": " goods ",
})
})
router.GET("/users/list", func(c *gin.Context) {
c.HTML(http.StatusOK, "users/list.html", gin.H{
"title": " user ",
})
})
router.Run(":8088")
}
- template/goods/list.html
{
{define "goods/list.html"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>
Product list page
</h1>
</body>
</html>
{
{end}}
- template/users/list.html
{
{define "users/list.html"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>
User list page
</h1>
</body>
</html>
{
{end}}
4 - static Static file processing
- static Static file loading :
router.Static("/static", "./static")
5、 ... and 、 Exit gracefully gin
- What is graceful exit : What we should do when we close the program
- analysis : Microservices -> Do one thing before or after startup , Change the current service ip Register the address and port number in the registry -> After the current service is stopped , Did not inform the registry
- gin Official documents exit gracefully :https://gin-gonic.com/docs/examples/graceful-restart-or-stop/
package main
import (
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/", func(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"msg": "pong",
})
})
go func() {
router.Run(":8088")
}()
// Do not use kill -9 command , The program cannot capture the signal
quit := make(chan os.Signal)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
// Processing subsequent logic
fmt.Println(" close server in ...")
fmt.Println(" Log out of service ...")
}
- stay cmd Run in , And implement CTRL+C
边栏推荐
- Without available task slots, what will happen to Flink's new tasks?
- mysql insert 存在即不插入语法
- method
- 使用binlog备份恢复myqsl数据
- Overwintering samples of game companies: has going to sea and boutique become a new growth point?
- gcc: error trying to exec ‘cc1‘: execvp: No such file or directory
- Dest0g3 520迎新赛web
- [try to hack] SQL injection less7 (into outfile and Boolean blind annotation)
- typeof与keyof
- 微信小程序开发学习4(视图与逻辑)
猜你喜欢
Overwintering samples of game companies: has going to sea and boutique become a new growth point?
Apipost :一款值得使用的利器
哔哩哔哩 直播分区页面 自动检索红包直播间并跳转
Component architecture project construction - gradle unified, dependent management and configuration
【Try to Hack】sql注入 Less7 (into outfile和布尔盲注)
Unable to install cloudera manager agent
Lua code add comment rule
It's just a TCC distributed transaction. Is it so difficult?
web测试之功能测试常用的方法有哪几种?有什么要点要注意?
Implementation of imx8mp kdump function
随机推荐
Surprise! Nearly 2million depositors' deposits were stolen by "face swiping". Look at your bank card. Are there these three kinds of risks?
Dynamic segment tree leetcode seven hundred and thirty-one
. Net uses its own Di batch injection service and backgroundservice
Introduction to kubernetes components
XSS cross site scripting attack
gcc: error trying to exec ‘cc1‘: execvp: No such file or directory
method
Golang - restful framework go restful
Circle Game
Sudo command executes commands with other users
2022.7.19-----leetcode. seven hundred and thirty-one
CDH cluster construction (6.3)
浅析云边端协同架构在安防视频领域的应用意义及场景
Study notes of pytorch deep learning practice: Circular neural network (basic chapter)
Chapter 8: monkey climbing N-level hierarchical recursion, finding the Zeng sequence of the simplest true fraction of the denominator [a, b], Fibonacci sequence recursion solution, Fibonacci sequence
EasyCVR接入国标GB28181设备,通道没有音频是什么原因?
App application testing methods and testing ideas
嗶哩嗶哩 直播分區頁面 自動檢索紅包直播間並跳轉
游戏公司的越冬样本:出海和精品化成为新的增长点?
Cve-2014-6271 "broken shell" vulnerability