项目作者: vicanso

项目描述 :
Concurrent limiter middleware for elton.
高级语言: Go
项目地址: git://github.com/vicanso/elton-concurrent-limiter.git
创建时间: 2019-02-22T13:20:23Z
项目社区:https://github.com/vicanso/elton-concurrent-limiter

开源协议:Apache License 2.0

下载


elton-concurrent-limiter

The middleware has been archived, please use the middleware of elton.

Build Status

Concurrent limiter for elton. It support to get lock value from five ways. Client IP, QueryString, Request Header, Route Params and Post Body.

  • IP The key’s name is :ip
  • QueryString The key’s name has prefix q:
  • Request Header The key’s name has prefix h:
  • Route Params The key’s name has prefix p:
  • Post Body The other’s key
  1. package main
  2. import (
  3. "bytes"
  4. "sync"
  5. "time"
  6. "github.com/vicanso/elton"
  7. concurrentLimiter "github.com/vicanso/elton-concurrent-limiter"
  8. )
  9. func main() {
  10. e := elton.New()
  11. m := new(sync.Map)
  12. limit := concurrentLimiter.New(concurrentLimiter.Config{
  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. }
  1. curl -XPOST 'http://127.0.0.1:7001/login'