maxconnshandler.go 878 B

1234567891011121314151617181920212223242526272829303132333435363738
  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. // MaxConns returns a middleware that limit the concurrent connections.
  9. func MaxConns(n int) func(http.Handler) http.Handler {
  10. if n <= 0 {
  11. return func(next http.Handler) http.Handler {
  12. return next
  13. }
  14. }
  15. return func(next http.Handler) http.Handler {
  16. latch := syncx.NewLimit(n)
  17. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  18. if latch.TryBorrow() {
  19. defer func() {
  20. if err := latch.Return(); err != nil {
  21. logx.Error(err)
  22. }
  23. }()
  24. next.ServeHTTP(w, r)
  25. } else {
  26. internal.Errorf(r, "concurrent connections over %d, rejected with code %d",
  27. n, http.StatusServiceUnavailable)
  28. w.WriteHeader(http.StatusServiceUnavailable)
  29. }
  30. })
  31. }
  32. }