当前位置:网站首页>【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 路由和回调
菜鸟实战,持续学习!
边栏推荐
- Hengyuan cloud_ Can aiphacode replace programmers?
- Minecraft插件服开服
- 使用递归函数求解字符串的逆置问题
- commands out of sync. did you run multiple statements at once
- Zipkin is easy to use
- CSDN Q & A_ Evaluation
- History of Web Technology
- Shengshihaotong and Guoao (Shenzhen) new energy Co., Ltd. build the charging pile industry chain
- Web技术发展史
- 汉诺塔问题的求解与分析
猜你喜欢
Introduction to the basic concept of queue and typical application examples
WSL安装、美化、网络代理和远程开发
C4D quick start tutorial - C4d mapping
Minecraft air Island service
zipkin 简单使用
C language replaces spaces in strings with%20
Web security -- core defense mechanism
C language custom type enumeration, Union (clever use of enumeration, calculation of union size)
Minecraft模组服开服
Kubesphere virtualization KSV installation experience
随机推荐
C4D quick start tutorial - C4d mapping
D interface and domain problems
[flask] ORM one-to-one relationship
判断是否是数独
PCL calculates the intersection of three mutually nonparallel planes
Application of kotlin - higher order function
Using recursive functions to solve the inverse problem of strings
Service de groupe minecraft
Honeypot attack and defense drill landing application scheme
Minecraft air Island service
Minecraft module service opening
统计字符串中各类字符的个数
OpenFeign 簡單使用
Googlenet network explanation and model building
Data asset management function
Leetcode sword finger offer brush questions - day 22
[blackmail virus data recovery] suffix Crylock blackmail virus
选择排序和插入排序
Nacos download, start and configure MySQL database
CSDN Q & A_ Evaluation