diff --git a/go.mod b/go.mod index f2c1c20..f693682 100644 --- a/go.mod +++ b/go.mod @@ -27,4 +27,5 @@ require ( github.com/mattn/go-sqlite3 v1.14.9 // indirect golang.org/x/crypto v0.0.0-20220321153916-2c7772ba3064 // indirect golang.org/x/text v0.3.7 // indirect + golang.org/x/time v0.0.0-20220411224347-583f2d630306 // indirect ) diff --git a/go.sum b/go.sum index eb911b2..0090077 100644 --- a/go.sum +++ b/go.sum @@ -172,6 +172,8 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/time v0.0.0-20220411224347-583f2d630306 h1:+gHMid33q6pen7kv9xvT+JRinntgeXO2AeZVd0AWD3w= +golang.org/x/time v0.0.0-20220411224347-583f2d630306/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= diff --git a/internal/server.go b/internal/server.go index bdd3844..b3f228a 100644 --- a/internal/server.go +++ b/internal/server.go @@ -24,7 +24,7 @@ func (server *HttpServer) SetServer(){ func (server *HttpServer) StartServer(port string){ fmt.Println("Server Started in: ", port) - log.Fatal(http.ListenAndServe(port, server.Router)) + log.Fatal(http.ListenAndServe(port, transport.LimitRequest(server.Router))) } func (server *HttpServer) SetRoutes(){ diff --git a/internal/users/transport/middlewares.go b/internal/users/transport/middlewares.go index 6cd6917..36f39cc 100644 --- a/internal/users/transport/middlewares.go +++ b/internal/users/transport/middlewares.go @@ -10,6 +10,8 @@ import ( "net/http" "strings" + "golang.org/x/time/rate" + "github.com/Edmartt/go-authentication-api/internal/users/models" "github.com/Edmartt/go-authentication-api/pkg/jwt" ) @@ -89,3 +91,17 @@ func IsAuthorized(handler http.HandlerFunc) http.HandlerFunc{ handler(w, r.WithContext(ctx)) } } + + + +func LimitRequest(next http.Handler) http.Handler{ + limit := rate.NewLimiter(0.3, 3) + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){ + if limit.Allow() == false{ + http.Error(w, http.StatusText(429), http.StatusTooManyRequests) + return + } + next.ServeHTTP(w, r) + }) +}