|
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- package mw
-
- import (
- "bytes"
- "io/ioutil"
-
- "github.com/gin-gonic/gin"
-
- "applet/app/utils"
- "applet/app/utils/cache"
- )
-
-
- func Limiter(c *gin.Context) {
- limit := 100
- ttl := 1
- ip := c.ClientIP()
-
- token := c.GetHeader("Authorization")
-
- method := c.Request.Method
- host := c.Request.Host
- uri := c.Request.URL.String()
-
- buf := make([]byte, 2048)
- num, _ := c.Request.Body.Read(buf)
- body := buf[:num]
-
- c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
- Md5 := utils.Md5(ip + token + method + host + uri + string(body))
- if cache.Exists(Md5) {
- c.AbortWithStatusJSON(429, gin.H{
- "code": 429,
- "msg": "don't repeat the request",
- "data": struct{}{},
- })
- return
- }
-
- go cache.SetEx(Md5, "0", ttl)
- key := "LIMITER_" + ip
- reqs, _ := cache.GetInt(key)
- if reqs >= limit {
- c.AbortWithStatusJSON(429, gin.H{
- "code": 429,
- "msg": "too many requests",
- "data": struct{}{},
- })
- return
- }
- if reqs > 0 {
- go cache.Incr(key)
- } else {
- go cache.SetEx(key, 1, ttl)
- }
- c.Next()
- go cache.Del(Md5)
- }
|