add request rate limiter

This commit is contained in:
ginuerzh
2022-09-14 19:53:21 +08:00
parent 45b7ac2021
commit 50d443049f
3 changed files with 26 additions and 6 deletions

View File

@ -7,17 +7,19 @@ import (
"github.com/go-gost/core/auth" "github.com/go-gost/core/auth"
"github.com/go-gost/core/bypass" "github.com/go-gost/core/bypass"
"github.com/go-gost/core/chain" "github.com/go-gost/core/chain"
"github.com/go-gost/core/limiter/rate"
"github.com/go-gost/core/logger" "github.com/go-gost/core/logger"
"github.com/go-gost/core/metadata" "github.com/go-gost/core/metadata"
) )
type Options struct { type Options struct {
Bypass bypass.Bypass Bypass bypass.Bypass
Router *chain.Router Router *chain.Router
Auth *url.Userinfo Auth *url.Userinfo
Auther auth.Authenticator Auther auth.Authenticator
TLSConfig *tls.Config RateLimiter rate.RateLimiter
Logger logger.Logger TLSConfig *tls.Config
Logger logger.Logger
} }
type Option func(opts *Options) type Option func(opts *Options)
@ -46,6 +48,12 @@ func AutherOption(auther auth.Authenticator) Option {
} }
} }
func RateLimiterOption(limiter rate.RateLimiter) Option {
return func(opts *Options) {
opts.RateLimiter = limiter
}
}
func TLSConfigOption(tlsConfig *tls.Config) Option { func TLSConfigOption(tlsConfig *tls.Config) Option {
return func(opts *Options) { return func(opts *Options) {
opts.TLSConfig = tlsConfig opts.TLSConfig = tlsConfig

10
limiter/rate/limiter.go Normal file
View File

@ -0,0 +1,10 @@
package rate
type Limiter interface {
Allow(n int) bool
Limit() float64
}
type RateLimiter interface {
Limiter(key string) Limiter
}

View File

@ -49,6 +49,8 @@ func GetFloat(md metadata.Metadata, key string) (v float64) {
} }
switch vv := md.Get(key).(type) { switch vv := md.Get(key).(type) {
case float64:
return vv
case int: case int:
return float64(vv) return float64(vv)
case string: case string: