concurrent limiter

并发请求限制,可以通过指定请求的参数,如IP、query的字段或者body等获取,限制同时并发性的提交请求,主要用于避免相同的请求多次提交。指定的Key分为以下几种:

  • :ip 客户的RealIP
  • h:key 从HTTP请求头中获取key的值
  • q:key 从HTTP的query中获取key的值
  • p:key 从路由的params中获取key的值
  • 其它的则从HTTP的Post data中获取key的值(只支持json)

Example

  1. package main
  2. import (
  3. "bytes"
  4. "sync"
  5. "time"
  6. "github.com/vicanso/elton"
  7. "github.com/vicanso/elton/middleware"
  8. )
  9. func main() {
  10. e := elton.New()
  11. m := new(sync.Map)
  12. limit := middleware.NewConcurrentLimiter(middleware.ConcurrentLimiterConfig{
  13. Keys: []string{
  14. ":ip",
  15. "h:X-Token",
  16. "q:type",
  17. "p:id",
  18. "account",
  19. },
  20. Lock: func(key string, c *elton.Context) (success bool, unlock func(), err error) {
  21. _, loaded := m.LoadOrStore(key, true)
  22. // the key not exists
  23. if !loaded {
  24. success = true
  25. unlock = func() {
  26. m.Delete(key)
  27. }
  28. }
  29. return
  30. },
  31. })
  32. e.POST("/login", limit, func(c *elton.Context) (err error) {
  33. time.Sleep(3 * time.Second)
  34. c.BodyBuffer = bytes.NewBufferString("hello world")
  35. return
  36. })
  37. err := e.ListenAndServe(":3000")
  38. if err != nil {
  39. panic(err)
  40. }
  41. }