requests.go 905 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package servlimit
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. type Requests struct {
  7. sync.RWMutex
  8. counter map[string]int
  9. lastTime map[string]int64
  10. cleanTime int64
  11. }
  12. func (r *Requests) Count(ip string) int {
  13. r.Lock()
  14. defer r.Unlock()
  15. if v, ok := r.counter[ip]; ok {
  16. return v
  17. }
  18. return 0
  19. }
  20. func (r *Requests) SetCount(ip string, count int) {
  21. r.Lock()
  22. defer r.Unlock()
  23. r.counter[ip] = count
  24. }
  25. func (r *Requests) Time(ip string) int64 {
  26. r.Lock()
  27. defer r.Unlock()
  28. if v, ok := r.lastTime[ip]; ok {
  29. return v
  30. }
  31. return 0
  32. }
  33. func (r *Requests) SetTime(ip string, time int64) {
  34. r.Lock()
  35. defer r.Unlock()
  36. r.lastTime[ip] = time
  37. }
  38. func (r *Requests) Cleanup() {
  39. r.Lock()
  40. defer r.Unlock()
  41. r.counter = map[string]int{}
  42. r.lastTime = map[string]int64{}
  43. r.cleanTime = time.Now().UTC().Unix()
  44. }
  45. func (r *Requests) CleanupHourly() {
  46. if (time.Now().UTC().Unix() - r.cleanTime) > 3600 {
  47. r.Cleanup()
  48. }
  49. }