From 8215fadbd96371bd7f7e679c66eb0ddcdec2655b Mon Sep 17 00:00:00 2001 From: antao Date: Sat, 25 May 2024 00:29:36 +0800 Subject: [PATCH] Add CORSMiddleware --- CMakeLists.txt | 4 +- lib/inc/drogon/CORSMiddleware.h | 72 +++++++++++++++++++++++++++++++++ lib/src/CORSMiddleware.cc | 0 3 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 lib/inc/drogon/CORSMiddleware.h create mode 100644 lib/src/CORSMiddleware.cc diff --git a/CMakeLists.txt b/CMakeLists.txt index c36d29a2..dc12d396 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -303,7 +303,8 @@ set(DROGON_SOURCES lib/src/WebSocketClientImpl.cc lib/src/WebSocketConnectionImpl.cc lib/src/YamlConfigAdapter.cc - lib/src/drogon_test.cc) + lib/src/drogon_test.cc + lib/src/CORSMiddleware.cc) set(private_headers lib/src/AOPAdvice.h lib/src/CacheFile.h @@ -588,6 +589,7 @@ set(DROGON_HEADERS lib/inc/drogon/PubSubService.h lib/inc/drogon/drogon_test.h lib/inc/drogon/RateLimiter.h + lib/inc/drogon/CORSMiddleware.h ${CMAKE_CURRENT_BINARY_DIR}/exports/drogon/exports.h) set(private_headers ${private_headers} diff --git a/lib/inc/drogon/CORSMiddleware.h b/lib/inc/drogon/CORSMiddleware.h new file mode 100644 index 00000000..61736ff0 --- /dev/null +++ b/lib/inc/drogon/CORSMiddleware.h @@ -0,0 +1,72 @@ +/** + * + * @file CORSMiddleware.h + * @author An Tao + * + * Copyright 2018, An Tao. All rights reserved. + * https://github.com/an-tao/drogon + * Use of this source code is governed by a MIT license + * that can be found in the License file. + * + * Drogon + * + */ +#pragma once +#include + +namespace drogon +{ +/** + * @brief This class represents a middleware that adds CORS headers to the + * response. + */ +class CORSMiddleware : public HttpMiddleware +{ + public: + CORSMiddleware() + { + } + + void invoke(const HttpRequestPtr &req, + MiddlewareNextCallback &&nextCb, + MiddlewareCallback &&mcb) override; + + void setAllowOrigins(const std::vector &origins) + { + allowOrigins_ = origins; + } + + void setAllowHeaders(const std::vector &headers) + { + allowHeaders_ = headers; + } + + void setAllowCredentials(bool allowCredentials) + { + allowCredentials_ = allowCredentials; + } + + void setExposeHeaders(const std::vector &headers) + { + exposeHeaders_ = headers; + } + + void setOriginRegex(const std::string ®ex) + { + originRegex_ = regex; + } + + void setMaxAge(int maxAge) + { + maxAge_ = maxAge; + } + + private: + std::vector allowOrigins_; + std::vector allowHeaders_; + std::vector exposeHeaders_; + bool allowCredentials_{false}; + std::string originRegex_; + int maxAge_{0}; +}; +} // namespace drogon diff --git a/lib/src/CORSMiddleware.cc b/lib/src/CORSMiddleware.cc new file mode 100644 index 00000000..e69de29b