1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
lmt := tollbooth.NewLimiter(10, &limiter.ExpirableOptions{ DefaultExpirationTTL: time.Hour * 24, })
func wrapGinLimitHandler(lmt *limiter.Limiter) gin.HandlerFunc { limitOptions := []string{"ip","token","device","version","platform","lang"} allowPathList := configure.Global.HttpConfig.AllowPathList denyPathList := configure.Global.HttpConfig.DenyPathList return func(c *gin.Context) { path := c.Request.URL.Path for _, v := range allowPathList { if strings.Contains(path, v) { c.Next() return } } for _, v := range denyPathList { if path == v { httpError := &errors.HTTPError{Message: lmt.GetMessage(), StatusCode: lmt.GetStatusCode()} c.Data(httpError.StatusCode, lmt.GetMessageContentType(), []byte(httpError.Message)) c.Abort() return } }
remoteIP := c.Request.Header.Get("X-Real-IP") if remoteIP == "" { remoteIP = c.ClientIP() } if remoteIP == "127.0.0.1" || remoteIP == "localhost" { c.Next() return }
var keys []string for _, v := range limitOptions { if strings.Contains(v, "ip") { keys = append(keys, remoteIP) } else if strings.Contains(v, "token") { token := c.GetHeader("Token") if token == "" { token = c.GetHeader("Access-Token") } keys = append(keys, token) } else if strings.Contains(v, "device") { keys = append(keys, c.GetHeader("Device-Id")) } else if strings.Contains(v, "version") { keys = append(keys, c.GetHeader("Appversion")) } else if strings.Contains(v, "platform") { keys = append(keys, c.GetHeader("Platform")) } else if strings.Contains(v, "lang") { keys = append(keys, c.GetHeader("Lang")) } } if len(keys) == 0 { keys = append(keys, remoteIP) } keys = append(keys, path)
httpError := tollbooth.LimitByKeys(lmt, keys) if httpError != nil { strKeys := path lqlog.WarnCtx(c.Request.Context(), "[wrapGinLimitHandler] keys: (%v)", strKeys) c.Data(httpError.StatusCode, lmt.GetMessageContentType(), []byte(httpError.Message)) if _, ok := LimitKeysMap.Load(strKeys); ok { } else { LimitKeysMap.Store(strKeys, "1") text := fmt.Sprintf(`"%s %s" trigger http limit, keys:%+v`, c.Request.Method, path, keys) text += fmt.Sprintf("\nAppversion: %v", c.GetHeader("Appversion")) text += fmt.Sprintf("\nPlatform: %v", c.GetHeader("Platform")) FeishuAlarmText(c, text) } c.Abort() } else { c.Next() } } }
|