servlimit.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. if requests > 0 {
  16. mRequests.CleanupHourly()
  17. ip := helpers.ClientIP(r)
  18. reqs := mRequests.Count(ip)
  19. ltime := mRequests.Time(ip)
  20. // Inc counter
  21. reqs = reqs + 1
  22. mRequests.SetCount(ip, reqs)
  23. // Reset counter
  24. if (time.Now().UTC().Unix() - ltime) >= 1 {
  25. reqs = 0
  26. mRequests.SetCount(ip, reqs)
  27. }
  28. // Restrict access
  29. if reqs >= requests {
  30. w.Header().Set("Retry-After", "1")
  31. w.WriteHeader(429)
  32. if _, err := w.Write([]byte("Too Many Requests\n")); err != nil {
  33. log.Printf("%s\n", err.Error())
  34. }
  35. return
  36. }
  37. mRequests.SetTime(ip, time.Now().UTC().Unix())
  38. }
  39. handler.ServeHTTP(w, r)
  40. })
  41. }