drogon
C++14/17-based HTTP application framework
Loading...
Searching...
No Matches
Hodor.h
Go to the documentation of this file.
1
13#pragma once
14#include <drogon/RateLimiter.h>
16#include <drogon/plugins/RealIpResolver.h>
18#include <drogon/CacheMap.h>
19#include <regex>
20#include <optional>
21
22namespace drogon
23{
24namespace plugin
25{
84class DROGON_EXPORT Hodor : public drogon::Plugin<Hodor>
85{
86 public:
87 Hodor()
88 {
89 }
90
91 void initAndStart(const Json::Value &config) override;
92 void shutdown() override;
93
100 std::function<std::optional<std::string>(const HttpRequestPtr &)> func)
101 {
102 userIdGetter_ = std::move(func);
103 }
104
111 std::function<HttpResponsePtr(const HttpRequestPtr &)> func)
112 {
113 rejectResponseFactory_ = std::move(func);
114 }
115
116 private:
117 struct LimitStrategy
118 {
119 std::regex urlsRegex;
120 size_t capacity{0};
121 size_t ipCapacity{0};
122 size_t userCapacity{0};
123 bool regexFlag{false};
124 RateLimiterPtr globalLimiterPtr;
125 std::unique_ptr<CacheMap<std::string, RateLimiterPtr>> ipLimiterMapPtr;
126 std::unique_ptr<CacheMap<std::string, RateLimiterPtr>>
127 userLimiterMapPtr;
128 };
129
130 LimitStrategy makeLimitStrategy(const Json::Value &config);
131 std::vector<LimitStrategy> limitStrategies_;
132 RateLimiterType algorithm_{RateLimiterType::kTokenBucket};
133 std::chrono::duration<double> timeUnit_{1.0};
134 bool multiThreads_{true};
135 bool useRealIpResolver_{false};
136 size_t limiterExpireTime_{600};
137 std::function<std::optional<std::string>(const drogon::HttpRequestPtr &)>
138 userIdGetter_;
139 std::function<HttpResponsePtr(const drogon::HttpRequestPtr &)>
140 rejectResponseFactory_;
141
142 RealIpResolver::CIDRs trustCIDRs_;
143
144 void onHttpRequest(const drogon::HttpRequestPtr &,
145 AdviceCallback &&,
146 AdviceChainCallback &&);
147 bool checkLimit(const drogon::HttpRequestPtr &req,
148 const LimitStrategy &strategy,
149 const trantor::InetAddress &ip,
150 const std::optional<std::string> &userId);
151 HttpResponsePtr rejectResponse_;
152};
153} // namespace plugin
154} // namespace drogon
The reflection base class for plugins.
Definition Plugin.h:132
void shutdown() override
void setRejectResponseFactory(std::function< HttpResponsePtr(const HttpRequestPtr &)> func)
the method is used to set a function to create the response when the rate limit is exceeded....
Definition Hodor.h:110
void setUserIdGetter(std::function< std::optional< std::string >(const HttpRequestPtr &)> func)
the method is used to set a function to get the user id from the request. users should call this meth...
Definition Hodor.h:99
void initAndStart(const Json::Value &config) override
Drogon Test is a minimal effort test framework developed because the major C++ test frameworks doesn'...
Definition Attribute.h:23