servlimit.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package servlimit
  2. import (
  3. "log"
  4. "net/http"
  5. "time"
  6. "github.com/vladimirok5959/golang-utils/utils/http/helpers"
  7. )
  8. var mRequests = &Requests{
  9. counter: map[string]int{},
  10. lastTime: map[string]int64{},
  11. cleanTime: time.Now().UTC().Unix(),
  12. }
  13. func ReqPerSecond(handler http.Handler, requests int) http.Handler {
  14. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  15. // Cleanup every hour
  16. if (time.Now().UTC().Unix() - mRequests.cleanTime) > 3600 {
  17. mRequests.Cleanup()
  18. }
  19. ip := helpers.ClientIP(r)
  20. reqs := mRequests.Count(ip)
  21. ltime := mRequests.Time(ip)
  22. // Inc counter
  23. reqs = reqs + 1
  24. mRequests.SetCount(ip, reqs)
  25. // Reset counter
  26. if (time.Now().UTC().Unix() - ltime) >= 1 {
  27. reqs = 0
  28. mRequests.SetCount(ip, 0)
  29. }
  30. // Restrict access
  31. if reqs >= requests {
  32. w.WriteHeader(429)
  33. if _, err := w.Write([]byte("Too Many Requests\n")); err != nil {
  34. log.Printf("%s\n", err.Error())
  35. }
  36. return
  37. }
  38. mRequests.SetTime(ip, time.Now().UTC().Unix())
  39. handler.ServeHTTP(w, r)
  40. })
  41. }