当前位置:网站首页>【Go实战基础】gin 如何自定义和使用一个中间件
【Go实战基础】gin 如何自定义和使用一个中间件
2022-07-02 06:33:00 【菜鸟实战】
目录
一、简介
实战场景: gin 如何自定义和使用一个中间件
二、知识点
gin 路由
字符串数组
数组循环
自定义中间件
http 状态码
三、菜鸟实战
马上安排!
1、创建 go文件
/*
* @Author: 菜鸟实战
* @Description: gin 如何自定义和使用一个中间件
*/
// 知识点:
// # gin 路由
// # 字符串数组
// # 数组循环
// # 自定义中间件
// # http 状态码
package main
// 导入包
import (
"fmt"
"github.com/gin-gonic/gin"
"runtime"
)
// IP 授权中间件
func IPAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 白名单
whiteIpList := []string{
"127.0.0.1",
}
flag := false
// 获取当前访问 ip, 与白名单 ip做比较
clientIp := c.ClientIP()
fmt.Printf("当前 client ip 为: %s \n", clientIp)
for _, whiteIp := range whiteIpList {
// 验证通过
if clientIp == whiteIp {
flag = true
break
}
}
// 验证未通过
if flag == false {
c.String(401, "client ip % is not in the white ip list", clientIp)
// 需要 abort
c.Abort()
}
}
}
// 主函数
func main() {
// 使用内置函数打印
println("Hello", "菜鸟实战")
println("实战场景: ", "gin 如何自定义和使用一个中间件")
// 初始化
r := gin.Default()
// 使用中间件
r.Use(IPAuthMiddleware())
// 添加 get 路由和回调
r.GET("/g", func(c *gin.Context) {
// 返回的 code 和 字符串返回
c.String(200, "这是一个使用了中间件的方法 \n")
})
// 使用包函数打印
fmt.Printf("版本: %s \n", runtime.Version())
// 启动框架程序, 默认 8080 端口
r.Run()
}
// curl 验证方式
// bind get
// curl -X GET "http://127.0.0.1:8080/g"
2、运行结果
Hello 菜鸟实战
实战场景: gin 如何自定义和使用一个中间件
[GIN-debug] Listening and serving HTTP on :8080
添加 get 路由和回调
菜鸟实战,持续学习!
边栏推荐
猜你喜欢
随机推荐
Multi version concurrency control mvcc of MySQL
Honeypot attack and defense drill landing application scheme
Oracle 相关统计
Illegal use of crawlers, an Internet company was terminated, the police came to the door, and 23 people were taken away
Concise analysis of redis source code 11 - Main IO threads and redis 6.0 multi IO threads
C# 高德地图 根据经纬度获取地址
kubernetes部署loki日志系统
Minecraft空岛服开服
kubeadm部署kubernetes v1.23.5集群
Getting started with k8s: building MySQL with Helm
gocv图片裁剪并展示
C4D quick start tutorial - Chamfer
C language custom type enumeration, Union (clever use of enumeration, calculation of union size)
Openfeign is easy to use
Web security -- core defense mechanism
Hengyuan cloud_ Can aiphacode replace programmers?
Analysis and solution of a classical Joseph problem
Gocv image cutting and display
Sqli labs level 1
[blackmail virus data recovery] suffix Rook3 blackmail virus









