Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rate limit middleware request #91

Open
anxuanzi opened this issue Jan 28, 2021 · 4 comments
Open

rate limit middleware request #91

anxuanzi opened this issue Jan 28, 2021 · 4 comments
Labels
enhancement New feature or request middleware

Comments

@anxuanzi
Copy link

anxuanzi commented Jan 28, 2021

Hi, I really like your framework and I'm currently using it for my project. I really need a rate limiter to control the traffic, I found some libraries that support Fasthttp. But I don't really know how to use them in Atreugo. Can you make a simple rate limiter middleware example to extend the Atreugo?

Libraries I found may be helpful:

@savsgio savsgio added enhancement New feature or request middleware labels Jan 28, 2021
@savsgio
Copy link
Owner

savsgio commented Jan 28, 2021

Hi @anxuanzi,

I will try to develop the middleware as soon as possible.

Thanks for use Atreugo 😉

@anxuanzi
Copy link
Author

Hi @anxuanzi,

I will try to develop the middleware as soon as possible.

Thanks for use Atreugo

Thank you! Looking forward to that~

@savsgio
Copy link
Owner

savsgio commented Feb 12, 2021

Hi @anxuanzi,

I don't forget the middleware, but lately, i don't have too much time.

I will try to has it soon.

@figuerom16
Copy link

figuerom16 commented Oct 5, 2024

Couldn't a rate limiter be something simple as this that we create ourselves?
I know we wouldn't be able to prefork because limiters map wouldn't be shared. Is there a better way?

package main

import (
	"errors"
	"net"
	"sync"

	"github.com/savsgio/atreugo/v11"
	"github.com/valyala/fasthttp"
	"golang.org/x/time/rate"
)

var limiters sync.Map

func RateLimiter(a *atreugo.RequestCtx) error {
	ip, _, err := net.SplitHostPort(a.RemoteAddr().String())
	if err != nil {
		return a.ErrorResponse(err, 555)
	}
	if ip == "127.0.0.1" || ip == "::1" {
		return a.Next()
	}
	limiter, _ := limiters.LoadOrStore(ip, rate.NewLimiter(10, 100))
	if !limiter.(*rate.Limiter).Allow() {
		return a.ErrorResponse(errors.New("too many requests"), fasthttp.StatusTooManyRequests)
	}
	return a.Next()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request middleware
Projects
None yet
Development

No branches or pull requests

3 participants