maxconnshandler.go 806 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package handler
  2. import (
  3. "net/http"
  4. "github.com/tal-tech/go-zero/core/logx"
  5. "github.com/tal-tech/go-zero/core/syncx"
  6. "github.com/tal-tech/go-zero/rest/internal"
  7. )
  8. func MaxConns(n int) func(http.Handler) http.Handler {
  9. if n <= 0 {
  10. return func(next http.Handler) http.Handler {
  11. return next
  12. }
  13. }
  14. return func(next http.Handler) http.Handler {
  15. latch := syncx.NewLimit(n)
  16. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  17. if latch.TryBorrow() {
  18. defer func() {
  19. if err := latch.Return(); err != nil {
  20. logx.Error(err)
  21. }
  22. }()
  23. next.ServeHTTP(w, r)
  24. } else {
  25. internal.Errorf(r, "concurrent connections over %d, rejected with code %d",
  26. n, http.StatusServiceUnavailable)
  27. w.WriteHeader(http.StatusServiceUnavailable)
  28. }
  29. })
  30. }
  31. }