Guardian is a Vapor 3 based Middleware that limits the number of requests from the client based on the IP address + access URL. It works by adding the client's IP address to the cache and counting the number of requests that the client can make within the lifecycle defined when the GuardianMiddleware is added, and returns HTTP 429 (too many requests) when the limit is reached. After the time limit expires, the request can be re-initiated,And support custom return data. The reason Guardian generates is because gatekeeper only supports vapor 2 , thanks very much to the original author! ๐บ
Consider that if there is a public IP address in the LAN, increase the unit threshold appropriately.
To include it in your package, add the following to your Package.swift
file.
let package = Package(
name: "Project",
dependencies: [
...
.package(url: "https://github.com/Jinxiansen/Guardian.git", from: "3.0.0"),
],
targets: [
.target(name: "App", dependencies: ["Guardian", ... ])
]
)
- Global use๏ผ
Guardian
Configurable fields: Maximum number of visits, time units, and cache to use.
If you do not provide your own cache, Guardian will create its own memory cache.
// Each api URL is limited to 20 times per minute
let guardian = GuardianMiddleware(rate: Rate(limit: 20, interval: .minute))
or
on configure.swift
- Import header files
import Guardian
- Join before services
var middlewares = MiddlewareConfig()
middlewares.use(GuardianMiddleware(rate: Rate(limit: 25, interval: .minute), closure: { (req) -> EventLoopFuture<Response>? in
let view = ["result":"429","message":"The request is too fast. Please try again later!"]
return try view.encode(for: req)
}))
services.register(middlewares)
- Routing group use:
let group = router.grouped(GuardianMiddleware(rate: Rate(limit: 25, interval: .minute)))
group.get("welcome") { req in
return "hello,world !"
}
Guardian adds support for custom return data, as in the following example:
Return a JSON object:
middlewares.use(GuardianMiddleware(rate: Rate(limit: 20, interval: .minute), closure: { (req) -> EventLoopFuture<Response>? in
let view = ["result":"429","message":"The request is too fast. Please try again later!"]
return try view.encode(for: req)
}))
or return a Leaf/Html web page:
middlewares.use(GuardianMiddleware(rate: Rate(limit: 25, interval: .minute), closure: { (req) -> EventLoopFuture<Response>? in
let view = try req.view().render("leaf/busy")
return try view.encode(for: req)
}))
or Custom returns other types of data...
Currently supported setup intervals are:
case .second
case .minute
case .hour
case .day
If you have any questions or suggestions you can raise one Issues or contact me:
Email : hi@jinxiansen.com
Twitter : @Jinxiansen
Guardian is released under the MIT license. See LICENSE for details.