当前位置:网站首页>【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 路由和回调
菜鸟实战,持续学习!
边栏推荐
猜你喜欢

Function ‘ngram‘ is not defined

Qunhui NAS configuring iSCSI storage

Mysql安装时mysqld.exe报`应用程序无法正常启动(0xc000007b)`

Honeypot attack and defense drill landing application scheme

C#钉钉开发:取得所有员工通讯录和发送工作通知

Kubesphere virtualization KSV installation experience

Flex layout

Data asset management function

Hengyuan cloud_ Can aiphacode replace programmers?

C language custom types - structure, bit segment (anonymous structure, self reference of structure, memory alignment of structure)
随机推荐
Using recursive functions to solve the inverse problem of strings
Solid principle: explanation and examples
C nail development: obtain all employee address books and send work notices
Application of kotlin - higher order function
随笔:RGB图像颜色分离(附代码)
kubernetes部署loki日志系统
OpenShift构建镜像
C call system sound beep~
Solution and analysis of Hanoi Tower problem
Essay: RGB image color separation (with code)
Programmer training, crazy job hunting, overtime ridiculed by colleagues deserve it
Flex layout
2022/2/14 summary
How to realize asynchronous programming in a synchronous way?
QT qtimer class
Sqli labs level 1
小米电视不能访问电脑共享文件的解决方案
C# 调用系统声音 嘀~
Leetcode sword finger offer brush questions - day 22
Honeypot attack and defense drill landing application scheme
