1515
1616#include < string>
1717#include < string_view>
18- #include < unordered_map >
18+ #include " re2/re2.h "
1919
2020#include " proxy_wasm_intrinsics.h"
2121
@@ -26,11 +26,14 @@ class ExampleRootContext : public RootContext {
2626 bool onStart (size_t ) override ;
2727 bool onConfigure (size_t ) override ;
2828 void onTick () override ;
29+
30+ std::optional<re2::RE2> path_match;
2931};
3032
3133class ExampleContext : public Context {
3234public:
33- explicit ExampleContext (uint32_t id, RootContext *root) : Context(id, root) {}
35+ explicit ExampleContext (uint32_t id, RootContext *root)
36+ : Context(id, root), root_(static_cast <ExampleRootContext *>(root)) {}
3437
3538 void onCreate () override ;
3639 FilterHeadersStatus onRequestHeaders (uint32_t headers, bool end_of_stream) override ;
@@ -40,6 +43,9 @@ class ExampleContext : public Context {
4043 void onDone () override ;
4144 void onLog () override ;
4245 void onDelete () override ;
46+
47+ private:
48+ const ExampleRootContext *root_;
4349};
4450static RegisterContextFactory register_ExampleContext (CONTEXT_FACTORY(ExampleContext),
4551 ROOT_FACTORY(ExampleRootContext),
@@ -62,8 +68,12 @@ bool ExampleRootContext::onStart(size_t) {
6268
6369bool ExampleRootContext::onConfigure (size_t ) {
6470 LOG_TRACE (" onConfigure" );
71+ // Start a timer.
6572 proxy_set_tick_period_milliseconds (1000 ); // 1 sec
66- return true ;
73+
74+ // Compile a regular expression.
75+ path_match.emplace (" /foo-([^/]+)/" );
76+ return path_match->ok ();
6777}
6878
6979void ExampleRootContext::onTick () { LOG_TRACE (" onTick" ); }
@@ -78,6 +88,11 @@ FilterHeadersStatus ExampleContext::onRequestHeaders(uint32_t, bool) {
7888 for (auto &p : pairs) {
7989 LOG_INFO (std::string (p.first ) + std::string (" -> " ) + std::string (p.second ));
8090 }
91+ // Regex.
92+ auto path = getRequestHeader (" :path" );
93+ if (path && re2::RE2::FullMatch (path->view (), *root_->path_match )) {
94+ sendLocalResponse (403 , " " , " Access forbidden." , {});
95+ }
8196 return FilterHeadersStatus::Continue;
8297}
8398
0 commit comments