From fc1e203c484f7dcea698a5373ee901ac7f05341c Mon Sep 17 00:00:00 2001 From: Gabriel De Los Rios Date: Mon, 3 Mar 2025 18:39:03 -0300 Subject: [PATCH] feat(ratelimit): impl --- rate_limit/rate_limit.go | 41 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 rate_limit/rate_limit.go diff --git a/rate_limit/rate_limit.go b/rate_limit/rate_limit.go new file mode 100644 index 0000000..61740dc --- /dev/null +++ b/rate_limit/rate_limit.go @@ -0,0 +1,41 @@ +package rate_limit + +import ( + "encoding/gob" + "os" + "time" +) + +const TIMEFRAME = 60 + +func TimeLeft(addr string) int64 { + timeLeft := int64(0) + file, err := os.OpenFile("addr_table.gob", os.O_RDWR|os.O_CREATE, 0644) + + if err == nil { + defer file.Close() + loadedData := make(map[string]int64) + gob.NewDecoder(file).Decode(&loadedData) + + if loadedData[addr] == 0 { + loadedData[addr] = time.Now().Unix() + saveDate(file, loadedData) + + } else { + t := time.Now().Unix() - loadedData[addr] + if t >= TIMEFRAME { + loadedData[addr] = time.Now().Unix() + saveDate(file, loadedData) + } else { + timeLeft = TIMEFRAME - t + } + } + + } + return timeLeft +} + +func saveDate(file *os.File, data map[string]int64) { + file.Seek(0, 0) + gob.NewEncoder(file).Encode(data) +}