concurrent limiter
并发请求限制,可以通过指定请求的参数,如IP、query的字段或者body等获取,限制同时并发性的提交请求,主要用于避免相同的请求多次提交。指定的Key分为以下几种:
:ip
客户的RealIPh:key
从HTTP请求头中获取key的值q:key
从HTTP的query中获取key的值p:key
从路由的params中获取key的值- 其它的则从HTTP的Post data中获取key的值(只支持json)
Example
package main
import (
"bytes"
"sync"
"time"
"github.com/vicanso/elton"
"github.com/vicanso/elton/middleware"
)
func main() {
e := elton.New()
m := new(sync.Map)
limit := middleware.NewConcurrentLimiter(middleware.ConcurrentLimiterConfig{
Keys: []string{
":ip",
"h:X-Token",
"q:type",
"p:id",
"account",
},
Lock: func(key string, c *elton.Context) (success bool, unlock func(), err error) {
_, loaded := m.LoadOrStore(key, true)
// the key not exists
if !loaded {
success = true
unlock = func() {
m.Delete(key)
}
}
return
},
})
e.POST("/login", limit, func(c *elton.Context) (err error) {
time.Sleep(3 * time.Second)
c.BodyBuffer = bytes.NewBufferString("hello world")
return
})
err := e.ListenAndServe(":3000")
if err != nil {
panic(err)
}
}