cocrrent.go 908 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package middleware
  2. import (
  3. "net/http"
  4. "sync"
  5. "github.com/gin-gonic/gin"
  6. "github.com/langgenius/dify-sandbox/internal/types"
  7. )
  8. func MaxWoker(max int) gin.HandlerFunc {
  9. queue := make(chan *gin.Context, max)
  10. for i := 0; i < max; i++ {
  11. go func() {
  12. for {
  13. select {
  14. case c := <-queue:
  15. c.Next()
  16. }
  17. }
  18. }()
  19. }
  20. return func(c *gin.Context) {
  21. queue <- c
  22. }
  23. }
  24. type MaxRequestIface struct {
  25. current int
  26. lock *sync.RWMutex
  27. }
  28. func MaxRequest(max int) gin.HandlerFunc {
  29. m := &MaxRequestIface{
  30. current: 0,
  31. lock: &sync.RWMutex{},
  32. }
  33. return func(c *gin.Context) {
  34. m.lock.RLock()
  35. if m.current >= max {
  36. m.lock.RUnlock()
  37. c.JSON(http.StatusServiceUnavailable, types.ErrorResponse(-503, "Too many requests"))
  38. c.Abort()
  39. return
  40. }
  41. m.lock.RUnlock()
  42. m.lock.Lock()
  43. m.current++
  44. m.lock.Unlock()
  45. c.Next()
  46. m.lock.Lock()
  47. m.current--
  48. m.lock.Unlock()
  49. }
  50. }