Go语言Gin框架 IP限流限速

介绍

go语言gin框架获取用户的用户请求统计用户请求的频率 记录上一次的时间 c *gin.Context 当频率超过一定 禁止该ip访问

核心代码

package config

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"sync"
	"time"
)

/**
 * @Author Administrator
 * @Description ip限速算法
 * @Date 2023/12/20 19:27
 * @Version 1.0
 */

// RequestInfo
// @Description: 请求信息
type RequestInfo struct {
   
	LastAccessTime time.Time // 上次访问时间
	RequestCount   int       // 请求计数
}

var (
	requestInfoMap = make(map[string]*RequestInfo) // IP到请求信息的映射
	mutex          = &sync.Mutex{
   }                 // 用于保护requestInfoMap的互斥锁
	maxRequests    = 30                            // 允许的最大请求数
	timeWindow     = 15 * time.Second			  // 时间窗口
)

// RateLimitMiddleware
//
//	@Description: ip限速算法
//	@param c
func RateLimitMiddleware(c *gin.Context) {
   
	ip := c.ClientIP()
	mutex.Lock()
	defer mutex.Unlock()

	// 检查IP是否在map中
	info, exists := requestInfoMap[ip]

	// 如果IP不存在,初始化并添加到map中
	if !exists {
   
		requestInfoMap[ip] = &RequestInfo{
   LastAccessTime: time.Now(), RequestCount: 1}
		return
	}

	// 如果IP存在,检查时间窗口
	if time.Since(info.LastAccessTime) > timeWindow {
   
		// 如果超过时间窗口,重置请求计数
		info.RequestCount = 1
		info.LastAccessTime = time.Now()
		return
	}

	// 如果在时间窗口内,增加请求计数
	info.RequestCount++

	// 如果请求计数超过限制,禁止访问
	if info.RequestCount > maxRequests {
   
		c.JSON(http.StatusTooManyRequests, gin.H{
   "error": "Too many requests"})
		c.Abort()
		return
	}

	// 更新最后访问时间
	info.LastAccessTime = time.Now()
}

主运行函数

记得使用基于Gin框架

r.Use(config.RateLimitMiddleware)

效果图

我设置的是15秒为一个单位 访问次数30及以内:

在这里插入图片描述

相关推荐

  1. go

    2023-12-21 06:32:06       32 阅读
  2. go语言gin框架的基本使用

    2023-12-21 06:32:06       70 阅读
  3. Go语言学习--Gin框架之响应

    2023-12-21 06:32:06       33 阅读
  4. Kong基于QPS、IP

    2023-12-21 06:32:06       39 阅读
  5. Go】令牌桶算法

    2023-12-21 06:32:06       40 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-21 06:32:06       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-21 06:32:06       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-21 06:32:06       82 阅读
  4. Python语言-面向对象

    2023-12-21 06:32:06       91 阅读

热门阅读

  1. Oracle中Null和‘‘的区别

    2023-12-21 06:32:06       65 阅读
  2. 12月20日,每日信息差

    2023-12-21 06:32:06       63 阅读
  3. 前端加密后端校验(MD5)

    2023-12-21 06:32:06       72 阅读
  4. 2019QWB growpjs

    2023-12-21 06:32:06       60 阅读
  5. linux下载yum和python

    2023-12-21 06:32:06       71 阅读
  6. ubuntu 重装/升级 eigen 教程

    2023-12-21 06:32:06       59 阅读
  7. 数据挖掘概述+探索+预处理(期末)

    2023-12-21 06:32:06       60 阅读
  8. 关于with torch.no_grad:的一些小问题

    2023-12-21 06:32:06       58 阅读
  9. 对相机位姿 导出 Tum 格式的位姿

    2023-12-21 06:32:06       56 阅读
  10. .env.development是什么

    2023-12-21 06:32:06       61 阅读
  11. vue中的内置指令和自定义指令

    2023-12-21 06:32:06       61 阅读
  12. Flink系列之:Upsert Kafka SQL 连接器

    2023-12-21 06:32:06       61 阅读