From 8992cf49b39b4c6f87abe3ba27139051d35d4691 Mon Sep 17 00:00:00 2001 From: Relintai Date: Thu, 10 Feb 2022 12:07:47 +0100 Subject: [PATCH] Removed the trantor namespace. --- core/containers/concurrent_task_queue.cpp | 3 +- core/containers/concurrent_task_queue.h | 3 - core/containers/lock_free_queue.h | 3 - core/containers/msg_buffer.cpp | 3 - core/containers/msg_buffer.h | 5 +- core/containers/serial_task_queue.cpp | 4 +- core/containers/serial_task_queue.h | 5 +- core/containers/task_queue.h | 3 +- core/log/async_file_logger.cpp | 4 - core/log/async_file_logger.h | 3 - core/log/log_stream.cpp | 5 +- core/log/log_stream.h | 2 - core/log/logger.cpp | 3 - core/log/logger.h | 64 +++-- core/loops/acceptor.cpp | 1 - core/loops/acceptor.h | 2 - core/loops/callbacks.h | 4 +- core/loops/channel.cpp | 3 +- core/loops/channel.h | 2 - core/loops/event_loop.cpp | 3 - core/loops/event_loop.h | 3 - core/loops/event_loop_thread.cpp | 1 - core/loops/event_loop_thread.h | 3 - core/loops/event_loop_thread_pool.cpp | 1 - core/loops/event_loop_thread_pool.h | 2 - core/loops/poller.cpp | 3 +- core/loops/poller.h | 2 - core/loops/poller/epoll_poller.cpp | 2 - core/loops/poller/epoll_poller.h | 2 - core/loops/poller/kqueue.cpp | 2 - core/loops/poller/kqueue.h | 3 - core/loops/poller/wepoll/README.md | 2 +- core/loops/timer.cpp | 2 - core/loops/timer.h | 2 - core/loops/timer_queue.cpp | 1 - core/loops/timer_queue.h | 2 - core/loops/timing_wheel.cpp | 3 +- core/loops/timing_wheel.h | 9 +- core/math/date.cpp | 5 +- core/math/date.h | 3 - core/math/math.h | 4 +- core/net/connections/tcp_connection_impl.cpp | 9 +- core/net/connections/tcp_connection_impl.h | 7 +- core/net/connector.cpp | 2 - core/net/connector.h | 3 - core/net/inet_address.cpp | 1 - core/net/inet_address.h | 4 - core/net/resolver.h | 5 +- core/net/resolvers/ares_resolver.cpp | 10 +- core/net/resolvers/ares_resolver.h | 15 +- core/net/resolvers/normal_resolver.cpp | 10 +- core/net/resolvers/normal_resolver.h | 11 +- core/net/socket.cpp | 1 - core/net/socket.h | 3 - core/net/tcp_client.cpp | 8 +- core/net/tcp_client.h | 3 - core/net/tcp_connection.h | 2 - core/net/tcp_server.cpp | 4 +- core/net/tcp_server.h | 7 +- tests/tests/AsyncFileLoggerTest.cc | 4 +- tests/tests/AsyncFileLoggerTest1.cc | 4 +- tests/tests/ConcurrentTaskQueueTest.cc | 2 +- tests/tests/DelayedSSLClientTest.cc | 8 +- tests/tests/DelayedSSLServerTest.cc | 2 +- tests/tests/DnsTest.cc | 28 +- tests/tests/KickoffTest.cc | 2 +- tests/tests/LoggerTest.cc | 2 +- tests/tests/RunInLoopTest1.cc | 2 +- tests/tests/RunInLoopTest2.cc | 2 +- tests/tests/RunOnQuitTest.cc | 2 +- tests/tests/SSLClientTest.cc | 8 +- tests/tests/SSLServerTest.cc | 2 +- tests/tests/SendfileTest.cc | 2 +- tests/tests/SerialTaskQueueTest1.cc | 6 +- tests/tests/SerialTaskQueueTest2.cc | 2 +- tests/tests/TcpClientTest.cc | 8 +- tests/tests/TcpServerTest.cc | 2 +- tests/tests/TimerTest.cc | 6 +- tests/tests/TimerTest1.cc | 6 +- tests/tests/TimingWheelTest.cc | 4 +- tests/unittests/DateUnittest.cc | 18 +- tests/unittests/InetAddressUnittest.cc | 2 +- tests/unittests/MsgBufferUnittest.cc | 2 +- tests/unittests/splitStringUnittest.cc | 22 +- web_backends/drogon/drogon/README.md | 2 +- .../drogon/drogon/examples/benchmark/main.cc | 2 +- .../drogon/examples/client_example/main.cc | 2 +- .../plugins/SimpleReverseProxy.cc | 2 +- .../websocket_client/WebSocketClient.cc | 2 +- .../drogon/lib/inc/drogon/HttpAppFramework.h | 18 +- .../drogon/drogon/lib/inc/drogon/HttpClient.h | 8 +- .../drogon/lib/inc/drogon/IOThreadStorage.h | 2 +- .../drogon/lib/inc/drogon/WebSocketClient.h | 6 +- .../lib/inc/drogon/WebSocketConnection.h | 4 +- .../drogon/lib/inc/drogon/drogon_test.h | 2 +- .../lib/inc/drogon/plugins/AccessLogger.h | 42 +-- .../drogon/lib/inc/drogon/plugins/Plugin.h | 2 +- .../drogon/lib/inc/drogon/utils/Utilities.h | 8 +- .../drogon/lib/inc/drogon/utils/string_view.h | 3 +- .../drogon/drogon/lib/inc/http/CacheFile.h | 2 +- .../drogon/drogon/lib/inc/http/CacheMap.h | 10 +- .../drogon/drogon/lib/inc/http/Cookie.h | 8 +- .../drogon/drogon/lib/inc/http/HttpRequest.h | 12 +- .../drogon/lib/inc/http/HttpRequestImpl.cc | 2 +- .../drogon/lib/inc/http/HttpRequestImpl.h | 28 +- .../drogon/lib/inc/http/HttpRequestParser.cc | 6 +- .../drogon/lib/inc/http/HttpRequestParser.h | 14 +- .../drogon/drogon/lib/inc/http/HttpResponse.h | 4 +- .../drogon/lib/inc/http/HttpResponseImpl.cc | 26 +- .../drogon/lib/inc/http/HttpResponseImpl.h | 22 +- .../drogon/lib/inc/http/HttpResponseParser.cc | 4 +- .../drogon/lib/inc/http/HttpResponseParser.h | 8 +- .../drogon/lib/inc/http/SessionManager.cc | 2 +- .../drogon/lib/inc/http/SessionManager.h | 6 +- .../drogon/drogon/lib/src/AccessLogger.cc | 64 ++--- .../drogon/lib/src/HttpAppFrameworkImpl.cc | 22 +- .../drogon/lib/src/HttpAppFrameworkImpl.h | 24 +- .../drogon/drogon/lib/src/HttpClientImpl.cc | 46 ++-- .../drogon/drogon/lib/src/HttpClientImpl.h | 22 +- .../drogon/drogon/lib/src/HttpServer.cc | 8 +- .../drogon/drogon/lib/src/HttpServer.h | 34 +-- .../drogon/drogon/lib/src/ListenerManager.cc | 12 +- .../drogon/drogon/lib/src/ListenerManager.h | 20 +- .../drogon/drogon/lib/src/PluginsManager.h | 2 +- .../drogon/drogon/lib/src/SharedLibManager.h | 6 +- .../drogon/drogon/lib/src/StaticFileRouter.cc | 2 +- .../drogon/drogon/lib/src/StaticFileRouter.h | 2 +- .../drogon/drogon/lib/src/TaskTimeoutFlag.cc | 2 +- .../drogon/drogon/lib/src/TaskTimeoutFlag.h | 6 +- .../drogon/drogon/lib/src/Utilities.cc | 8 +- .../drogon/lib/src/WebSocketClientImpl.cc | 38 +-- .../drogon/lib/src/WebSocketClientImpl.h | 24 +- .../drogon/lib/src/WebSocketConnectionImpl.cc | 14 +- .../drogon/lib/src/WebSocketConnectionImpl.h | 24 +- .../lib/src/WebsocketControllersRouter.h | 2 +- .../drogon/drogon/lib/src/impl_forwards.h | 4 +- .../lib/tests/integration_test/client/main.cc | 2 +- .../integration_test/server/PipeliningTest.cc | 2 +- .../integration_test/server/TimeFilter.cc | 8 +- .../server/a-directory/page.html | 256 +++++++++--------- .../server/api_v1_CoroTest.cc | 2 +- .../tests/integration_test/server/index.html | 256 +++++++++--------- .../lib/tests/integration_test/server/main.cc | 6 +- .../lib/tests/unittests/CacheMapTest.cc | 2 +- .../drogon/lib/tests/unittests/CookieTest.cc | 2 +- .../lib/tests/unittests/MsgBufferTest.cc | 2 +- .../drogon/drogon/lib/tests/unittests/main.cc | 2 +- web_backends/drogon/drogon_web_server.cpp | 24 +- web_backends/drogon/drogon_web_server.h | 16 +- .../drogon/trantor/utils/NonCopyable.h | 4 - 150 files changed, 770 insertions(+), 894 deletions(-) diff --git a/core/containers/concurrent_task_queue.cpp b/core/containers/concurrent_task_queue.cpp index 4e44b05..0ceaa4a 100644 --- a/core/containers/concurrent_task_queue.cpp +++ b/core/containers/concurrent_task_queue.cpp @@ -28,14 +28,13 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#include #include "concurrent_task_queue.h" #include "core/log/logger.h" +#include #ifdef __linux__ #include #endif -using namespace trantor; ConcurrentTaskQueue::ConcurrentTaskQueue(size_t threadNum, const std::string &name) : queueCount_(threadNum), queueName_(name), stop_(false) { diff --git a/core/containers/concurrent_task_queue.h b/core/containers/concurrent_task_queue.h index b954e95..e8ed695 100644 --- a/core/containers/concurrent_task_queue.h +++ b/core/containers/concurrent_task_queue.h @@ -37,7 +37,6 @@ #include #include -namespace trantor { /** * @brief This class implements a task queue running in parallel. Basically this * can be called a threads pool. @@ -99,5 +98,3 @@ private: std::atomic_bool stop_; void queueFunc(int queueNum); }; - -} // namespace trantor diff --git a/core/containers/lock_free_queue.h b/core/containers/lock_free_queue.h index 1804033..0b56a42 100644 --- a/core/containers/lock_free_queue.h +++ b/core/containers/lock_free_queue.h @@ -34,7 +34,6 @@ #include #include -namespace trantor { /** * @brief This class template represents a lock-free multiple producers single * consumer queue @@ -122,5 +121,3 @@ private: std::atomic head_; std::atomic tail_; }; - -} // namespace trantor diff --git a/core/containers/msg_buffer.cpp b/core/containers/msg_buffer.cpp index 1363f1e..b72fb19 100644 --- a/core/containers/msg_buffer.cpp +++ b/core/containers/msg_buffer.cpp @@ -42,10 +42,7 @@ #include #include -using namespace trantor; -namespace trantor { static constexpr size_t kBufferOffset{ 8 }; -} MsgBuffer::MsgBuffer(size_t len) : head_(kBufferOffset), initCap_(len), buffer_(len + head_), tail_(head_) { diff --git a/core/containers/msg_buffer.h b/core/containers/msg_buffer.h index 04ceac0..400d8b6 100644 --- a/core/containers/msg_buffer.h +++ b/core/containers/msg_buffer.h @@ -40,8 +40,6 @@ using ssize_t = long long; #endif -namespace trantor -{ static constexpr size_t kBufferDefaultLength{2048}; static constexpr char CRLF[]{"\r\n"}; @@ -379,12 +377,11 @@ inline void swap(MsgBuffer &one, MsgBuffer &two) noexcept { one.swap(two); } -} // namespace trantor namespace std { template <> -inline void swap(trantor::MsgBuffer &one, trantor::MsgBuffer &two) noexcept +inline void swap(MsgBuffer &one, MsgBuffer &two) noexcept { one.swap(two); } diff --git a/core/containers/serial_task_queue.cpp b/core/containers/serial_task_queue.cpp index c4b2ee7..35a3cbe 100644 --- a/core/containers/serial_task_queue.cpp +++ b/core/containers/serial_task_queue.cpp @@ -33,7 +33,8 @@ #ifdef __linux__ #include #endif -namespace trantor { + + SerialTaskQueue::SerialTaskQueue(const std::string &name) : queueName_(name.empty() ? "SerailTaskQueue" : name), loopThread_(queueName_) { @@ -62,4 +63,3 @@ void SerialTaskQueue::waitAllTasksFinished() { }); } -} // namespace trantor diff --git a/core/containers/serial_task_queue.h b/core/containers/serial_task_queue.h index 5b9162a..953257d 100644 --- a/core/containers/serial_task_queue.h +++ b/core/containers/serial_task_queue.h @@ -36,8 +36,8 @@ #include #include #include -namespace trantor -{ + + /** * @brief This class represents a task queue in which all tasks are executed one * by one. @@ -112,4 +112,3 @@ class SerialTaskQueue : public TaskQueue EventLoopThread loopThread_; bool stop_{false}; }; -} // namespace trantor diff --git a/core/containers/task_queue.h b/core/containers/task_queue.h index 14204f1..57e412b 100644 --- a/core/containers/task_queue.h +++ b/core/containers/task_queue.h @@ -34,7 +34,6 @@ #include #include -namespace trantor { /** * @brief This class is a pure virtual class that can be implemented as a * SerialTaskQueue or a ConcurrentTaskQueue. @@ -74,4 +73,4 @@ public: virtual ~TaskQueue() { } }; -} // namespace trantor + diff --git a/core/log/async_file_logger.cpp b/core/log/async_file_logger.cpp index 42127d5..b7744ff 100644 --- a/core/log/async_file_logger.cpp +++ b/core/log/async_file_logger.cpp @@ -40,13 +40,9 @@ #include #include -namespace trantor { static constexpr std::chrono::seconds kLogFlushTimeout{ 1 }; static constexpr size_t kMemBufferSize{ 4 * 1024 * 1024 }; extern const char *strerror_tl(int savedErrno); -} // namespace trantor - -using namespace trantor; AsyncFileLogger::AsyncFileLogger() : logBufferPtr_(new std::string), nextBufferPtr_(new std::string) { diff --git a/core/log/async_file_logger.h b/core/log/async_file_logger.h index f391d7a..0630ddd 100644 --- a/core/log/async_file_logger.h +++ b/core/log/async_file_logger.h @@ -39,7 +39,6 @@ #include #include -namespace trantor { using StringPtr = std::shared_ptr; using StringPtrQueue = std::queue; @@ -159,5 +158,3 @@ protected: uint64_t lostCounter_{ 0 }; void swapBuffer(); }; - -} // namespace trantor diff --git a/core/log/log_stream.cpp b/core/log/log_stream.cpp index be2131d..12afd16 100644 --- a/core/log/log_stream.cpp +++ b/core/log/log_stream.cpp @@ -38,10 +38,8 @@ #include #include -using namespace trantor; -using namespace trantor::detail; +using namespace detail; -namespace trantor { namespace detail { const char digits[] = "9876543210123456789"; const char *zero = digits + 9; @@ -89,7 +87,6 @@ template class FixedBuffer; template class FixedBuffer; } // namespace detail -} // namespace trantor template const char *FixedBuffer::debugString() { diff --git a/core/log/log_stream.h b/core/log/log_stream.h index 8ef1255..60e67de 100644 --- a/core/log/log_stream.h +++ b/core/log/log_stream.h @@ -36,7 +36,6 @@ #include // memcpy #include -namespace trantor { namespace detail { static constexpr size_t kSmallBuffer{ 4000 }; static constexpr size_t kLargeBuffer{ 4000 * 1000 }; @@ -260,4 +259,3 @@ inline LogStream &operator<<(LogStream &s, const Fmt &fmt) { return s; } -} // namespace trantor diff --git a/core/log/logger.cpp b/core/log/logger.cpp index 05aeed2..92ed214 100644 --- a/core/log/logger.cpp +++ b/core/log/logger.cpp @@ -88,7 +88,6 @@ void RLogger::_log_index_error(const char *p_function, const char *p_file, int p printf("!INDEX ERROR: (%s) %s:%d :: index: %d/%d. %s\n", p_file, p_function, p_line, index, size, str); } -namespace trantor { // helper class for known string length at compile time class T { public: @@ -120,8 +119,6 @@ inline LogStream &operator<<(LogStream &s, const Logger::SourceFile &v) { s.append(v.data_, v.size_); return s; } -} // namespace trantor -using namespace trantor; static thread_local uint64_t lastSecond_{ 0 }; static thread_local char lastTimeString_[32] = { 0 }; diff --git a/core/log/logger.h b/core/log/logger.h index bc3beec..13ca6b8 100644 --- a/core/log/logger.h +++ b/core/log/logger.h @@ -61,7 +61,6 @@ public: static void _log_index_error(const char *p_function, const char *p_file, int p_line, const int index, const int size, const char *str); }; -namespace trantor { /** * @brief This class implements log functions. * @@ -249,64 +248,64 @@ private: #ifdef NDEBUG #define LOG_TRACE \ if (0) \ - trantor::Logger(__FILE__, __LINE__, trantor::Logger::kTrace, __func__) \ + Logger(__FILE__, __LINE__, Logger::kTrace, __func__) \ .stream() #else #define LOG_TRACE \ - if (trantor::Logger::logLevel() <= trantor::Logger::kTrace) \ - trantor::Logger(__FILE__, __LINE__, trantor::Logger::kTrace, __func__) \ + if (Logger::logLevel() <= Logger::kTrace) \ + Logger(__FILE__, __LINE__, Logger::kTrace, __func__) \ .stream() #define LOG_TRACE_TO(index) \ - if (trantor::Logger::logLevel() <= trantor::Logger::kTrace) \ - trantor::Logger(__FILE__, __LINE__, trantor::Logger::kTrace, __func__) \ + if (Logger::logLevel() <= Logger::kTrace) \ + Logger(__FILE__, __LINE__, Logger::kTrace, __func__) \ .setIndex(index) \ .stream() #endif #define LOG_DEBUG \ - if (trantor::Logger::logLevel() <= trantor::Logger::kDebug) \ - trantor::Logger(__FILE__, __LINE__, trantor::Logger::kDebug, __func__) \ + if (Logger::logLevel() <= Logger::kDebug) \ + Logger(__FILE__, __LINE__, Logger::kDebug, __func__) \ .stream() #define LOG_DEBUG_TO(index) \ - if (trantor::Logger::logLevel() <= trantor::Logger::kDebug) \ - trantor::Logger(__FILE__, __LINE__, trantor::Logger::kDebug, __func__) \ + if (Logger::logLevel() <= Logger::kDebug) \ + Logger(__FILE__, __LINE__, Logger::kDebug, __func__) \ .setIndex(index) \ .stream() #define LOG_INFO \ - if (trantor::Logger::logLevel() <= trantor::Logger::kInfo) \ - trantor::Logger(__FILE__, __LINE__).stream() + if (Logger::logLevel() <= Logger::kInfo) \ + Logger(__FILE__, __LINE__).stream() #define LOG_INFO_TO(index) \ - if (trantor::Logger::logLevel() <= trantor::Logger::kInfo) \ - trantor::Logger(__FILE__, __LINE__).setIndex(index).stream() + if (Logger::logLevel() <= Logger::kInfo) \ + Logger(__FILE__, __LINE__).setIndex(index).stream() #define LOG_WARN \ - trantor::Logger(__FILE__, __LINE__, trantor::Logger::kWarn).stream() + Logger(__FILE__, __LINE__, Logger::kWarn).stream() #define LOG_WARN_TO(index) \ - trantor::Logger(__FILE__, __LINE__, trantor::Logger::kWarn) \ + Logger(__FILE__, __LINE__, Logger::kWarn) \ .setIndex(index) \ .stream() #define LOG_ERROR \ - trantor::Logger(__FILE__, __LINE__, trantor::Logger::kError).stream() + Logger(__FILE__, __LINE__, Logger::kError).stream() #define LOG_ERROR_TO(index) \ - trantor::Logger(__FILE__, __LINE__, trantor::Logger::kError) \ + Logger(__FILE__, __LINE__, Logger::kError) \ .setIndex(index) \ .stream() #define LOG_FATAL \ - trantor::Logger(__FILE__, __LINE__, trantor::Logger::kFatal).stream() + Logger(__FILE__, __LINE__, Logger::kFatal).stream() #define LOG_FATAL_TO(index) \ - trantor::Logger(__FILE__, __LINE__, trantor::Logger::kFatal) \ + Logger(__FILE__, __LINE__, Logger::kFatal) \ .setIndex(index) \ .stream() -#define LOG_SYSERR trantor::Logger(__FILE__, __LINE__, true).stream() +#define LOG_SYSERR Logger(__FILE__, __LINE__, true).stream() #define LOG_SYSERR_TO(index) \ - trantor::Logger(__FILE__, __LINE__, true).setIndex(index).stream() + Logger(__FILE__, __LINE__, true).setIndex(index).stream() -#define LOG_RAW trantor::RawLogger().stream() -#define LOG_RAW_TO(index) trantor::RawLogger().setIndex(index).stream() +#define LOG_RAW RawLogger().stream() +#define LOG_RAW_TO(index) RawLogger().setIndex(index).stream() #define LOG_TRACE_IF(cond) \ - if ((trantor::Logger::logLevel() <= trantor::Logger::kTrace) && (cond)) \ - trantor::Logger(__FILE__, __LINE__, trantor::Logger::kTrace, __func__) \ + if ((Logger::logLevel() <= Logger::kTrace) && (cond)) \ + Logger(__FILE__, __LINE__, Logger::kTrace, __func__) \ .stream() #define LOG_DEBUG_IF(cond) \ if ((Tensor::Logger::logLevel() <= Tensor::Logger::kDebug) && (cond)) \ @@ -328,7 +327,7 @@ private: #ifdef NDEBUG #define DLOG_TRACE \ if (0) \ - trantor::Logger(__FILE__, __LINE__, trantor::Logger::kTrace, __func__) \ + Logger(__FILE__, __LINE__, Logger::kTrace, __func__) \ .stream() #define DLOG_DEBUG \ if (0) \ @@ -349,7 +348,7 @@ private: #define DLOG_TRACE_IF(cond) \ if (0) \ - trantor::Logger(__FILE__, __LINE__, trantor::Logger::kTrace, __func__) \ + Logger(__FILE__, __LINE__, Logger::kTrace, __func__) \ .stream() #define DLOG_DEBUG_IF(cond) \ if (0) \ @@ -369,8 +368,8 @@ private: Tensor::Logger(__FILE__, __LINE__, Tensor::Logger::kFatal).stream() #else #define DLOG_TRACE \ - if (trantor::Logger::logLevel() <= trantor::Logger::kTrace) \ - trantor::Logger(__FILE__, __LINE__, trantor::Logger::kTrace, __func__) \ + if (Logger::logLevel() <= Logger::kTrace) \ + Logger(__FILE__, __LINE__, Logger::kTrace, __func__) \ .stream() #define DLOG_DEBUG \ if (Tensor::Logger::logLevel() <= Tensor::Logger::kDebug) \ @@ -387,8 +386,8 @@ private: Tensor::Logger(__FILE__, __LINE__, Tensor::Logger::kFatal).stream() #define DLOG_TRACE_IF(cond) \ - if ((trantor::Logger::logLevel() <= trantor::Logger::kTrace) && (cond)) \ - trantor::Logger(__FILE__, __LINE__, trantor::Logger::kTrace, __func__) \ + if ((Logger::logLevel() <= Logger::kTrace) && (cond)) \ + Logger(__FILE__, __LINE__, Logger::kTrace, __func__) \ .stream() #define DLOG_DEBUG_IF(cond) \ if ((Tensor::Logger::logLevel() <= Tensor::Logger::kDebug) && (cond)) \ @@ -409,6 +408,5 @@ private: #endif const char *strerror_tl(int savedErrno); -} // namespace trantor #endif diff --git a/core/loops/acceptor.cpp b/core/loops/acceptor.cpp index bf955d7..25d7824 100644 --- a/core/loops/acceptor.cpp +++ b/core/loops/acceptor.cpp @@ -29,7 +29,6 @@ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "acceptor.h" -using namespace trantor; #ifndef O_CLOEXEC #define O_CLOEXEC O_NOINHERIT diff --git a/core/loops/acceptor.h b/core/loops/acceptor.h index 33e769b..c194b21 100644 --- a/core/loops/acceptor.h +++ b/core/loops/acceptor.h @@ -36,7 +36,6 @@ #include "event_loop.h" #include -namespace trantor { using NewConnectionCallback = std::function; class Acceptor { protected: @@ -71,4 +70,3 @@ protected: Channel acceptChannel_; void readCallback(); }; -} // namespace trantor diff --git a/core/loops/callbacks.h b/core/loops/callbacks.h index 846e161..1648dbc 100644 --- a/core/loops/callbacks.h +++ b/core/loops/callbacks.h @@ -32,8 +32,7 @@ #include #include -namespace trantor -{ + enum class SSLError { kSSLHandshakeError, @@ -56,4 +55,3 @@ using HighWaterMarkCallback = std::function; using SSLErrorCallback = std::function; -} // namespace trantor diff --git a/core/loops/channel.cpp b/core/loops/channel.cpp index 7d07edf..8ed70b8 100644 --- a/core/loops/channel.cpp +++ b/core/loops/channel.cpp @@ -43,7 +43,7 @@ #include #endif #include -namespace trantor { + const int Channel::kNoneEvent = 0; const int Channel::kReadEvent = POLLIN | POLLPRI; @@ -111,4 +111,3 @@ void Channel::handleEventSafely() { } } -} // namespace trantor diff --git a/core/loops/channel.h b/core/loops/channel.h index a7adf7b..e073466 100644 --- a/core/loops/channel.h +++ b/core/loops/channel.h @@ -35,7 +35,6 @@ #include #include -namespace trantor { class EventLoop; /** * @brief This class is used to implement reactor pattern. A Channel object @@ -304,4 +303,3 @@ private: std::weak_ptr tie_; bool tied_; }; -} // namespace trantor diff --git a/core/loops/event_loop.cpp b/core/loops/event_loop.cpp index 378fd0e..ffdf63f 100644 --- a/core/loops/event_loop.cpp +++ b/core/loops/event_loop.cpp @@ -57,7 +57,6 @@ using ssize_t = long long; #include #include -namespace trantor { #ifdef __linux__ int createEventfd() { int evtfd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); @@ -334,5 +333,3 @@ void EventLoop::runOnQuit(Func &&cb) { void EventLoop::runOnQuit(const Func &cb) { funcsOnQuit_.enqueue(cb); } - -} // namespace trantor diff --git a/core/loops/event_loop.h b/core/loops/event_loop.h index 6e26d34..5d6d779 100644 --- a/core/loops/event_loop.h +++ b/core/loops/event_loop.h @@ -42,7 +42,6 @@ #include #include -namespace trantor { class Poller; class TimerQueue; class Channel; @@ -323,5 +322,3 @@ private: #endif EventLoop **threadLocalLoopPtr_; }; - -} // namespace trantor diff --git a/core/loops/event_loop_thread.cpp b/core/loops/event_loop_thread.cpp index 205227a..a39f5a5 100644 --- a/core/loops/event_loop_thread.cpp +++ b/core/loops/event_loop_thread.cpp @@ -34,7 +34,6 @@ #include #endif -using namespace trantor; EventLoopThread::EventLoopThread(const std::string &threadName) : loop_(nullptr), loopThreadName_(threadName), diff --git a/core/loops/event_loop_thread.h b/core/loops/event_loop_thread.h index 26ffde3..5a04a90 100644 --- a/core/loops/event_loop_thread.h +++ b/core/loops/event_loop_thread.h @@ -37,7 +37,6 @@ #include #include -namespace trantor { /** * @brief This class represents an event loop thread. * @@ -86,5 +85,3 @@ private: std::once_flag once_; std::thread thread_; }; - -} // namespace trantor diff --git a/core/loops/event_loop_thread_pool.cpp b/core/loops/event_loop_thread_pool.cpp index 81edc4f..ebd5c3a 100644 --- a/core/loops/event_loop_thread_pool.cpp +++ b/core/loops/event_loop_thread_pool.cpp @@ -30,7 +30,6 @@ #include "event_loop_thread_pool.h" -using namespace trantor; EventLoopThreadPool::EventLoopThreadPool(size_t threadNum, const std::string &name) : loopIndex_(0) { diff --git a/core/loops/event_loop_thread_pool.h b/core/loops/event_loop_thread_pool.h index 429d5eb..2fcf8e9 100644 --- a/core/loops/event_loop_thread_pool.h +++ b/core/loops/event_loop_thread_pool.h @@ -34,7 +34,6 @@ #include #include -namespace trantor { /** * @brief This class represents a pool of EventLoopThread objects * @@ -108,4 +107,3 @@ private: std::vector > loopThreadVector_; size_t loopIndex_; }; -} // namespace trantor diff --git a/core/loops/poller.cpp b/core/loops/poller.cpp index 55763d5..a4e8f60 100644 --- a/core/loops/poller.cpp +++ b/core/loops/poller.cpp @@ -37,7 +37,8 @@ #else #include "poller/kqueue.h" #endif -using namespace trantor; + + Poller *Poller::newPoller(EventLoop *loop) { #if defined __linux__ || defined _WIN32 return new EpollPoller(loop); diff --git a/core/loops/poller.h b/core/loops/poller.h index dcf45dd..1d86f9f 100644 --- a/core/loops/poller.h +++ b/core/loops/poller.h @@ -35,7 +35,6 @@ #include #include -namespace trantor { class Channel; #ifdef _WIN32 using EventCallback = std::function; @@ -70,4 +69,3 @@ public: private: EventLoop *ownerLoop_; }; -} // namespace trantor diff --git a/core/loops/poller/epoll_poller.cpp b/core/loops/poller/epoll_poller.cpp index 1a4a00d..28d5af0 100644 --- a/core/loops/poller/epoll_poller.cpp +++ b/core/loops/poller/epoll_poller.cpp @@ -48,7 +48,6 @@ #define EPOLL_CLOEXEC _O_NOINHERIT #endif -namespace trantor { #if defined __linux__ || defined _WIN32 #if defined __linux__ @@ -219,4 +218,3 @@ void EpollPoller::removeChannel(Channel *) { } #endif -} // namespace trantor diff --git a/core/loops/poller/epoll_poller.h b/core/loops/poller/epoll_poller.h index 2d7e10d..9272daa 100644 --- a/core/loops/poller/epoll_poller.h +++ b/core/loops/poller/epoll_poller.h @@ -39,7 +39,6 @@ using EventList = std::vector; #endif -namespace trantor { class Channel; class EpollPoller : public Poller { @@ -74,4 +73,3 @@ private: void fillActiveChannels(int numEvents, ChannelList *activeChannels) const; #endif }; -} // namespace trantor diff --git a/core/loops/poller/kqueue.cpp b/core/loops/poller/kqueue.cpp index b50a25c..b40064a 100644 --- a/core/loops/poller/kqueue.cpp +++ b/core/loops/poller/kqueue.cpp @@ -41,7 +41,6 @@ #include #endif -namespace trantor { #ifdef USE_KQUEUE namespace { const int kNew = -1; @@ -232,4 +231,3 @@ void KQueue::removeChannel(Channel *) { void KQueue::resetAfterFork() { } #endif -} // namespace trantor diff --git a/core/loops/poller/kqueue.h b/core/loops/poller/kqueue.h index 5f4bdbd..83edb0c 100644 --- a/core/loops/poller/kqueue.h +++ b/core/loops/poller/kqueue.h @@ -41,7 +41,6 @@ using EventList = std::vector; #endif -namespace trantor { class Channel; class KQueue : public Poller { @@ -65,5 +64,3 @@ private: void update(Channel *channel); #endif }; - -} // namespace trantor \ No newline at end of file diff --git a/core/loops/poller/wepoll/README.md b/core/loops/poller/wepoll/README.md index fc9ce85..f8b86a3 100644 --- a/core/loops/poller/wepoll/README.md +++ b/core/loops/poller/wepoll/README.md @@ -2,7 +2,7 @@ This library is based on [wepoll v1.5.8](https://github.com/piscisaureus/wepoll/commit/0598a791bf9cbbf480793d778930fc635b044980). -An eventfd-like mechanism is added to it. After making the changes, we can wake up `trantor::EventLoop` from the epoll_wait() function. +An eventfd-like mechanism is added to it. After making the changes, we can wake up `EventLoop` from the epoll_wait() function. ## Modifications diff --git a/core/loops/timer.cpp b/core/loops/timer.cpp index 825f066..ac2d74d 100644 --- a/core/loops/timer.cpp +++ b/core/loops/timer.cpp @@ -32,7 +32,6 @@ #include "core/log/logger.h" #include "core/loops/event_loop.h" -namespace trantor { std::atomic Timer::timersCreated_ = ATOMIC_VAR_INIT(InvalidTimerId); Timer::Timer(const TimerCallback &cb, const TimePoint &when, @@ -68,4 +67,3 @@ bool Timer::operator<(const Timer &t) const { bool Timer::operator>(const Timer &t) const { return when_ > t.when_; } -} // namespace trantor diff --git a/core/loops/timer.h b/core/loops/timer.h index a3a17e0..7cef2ef 100644 --- a/core/loops/timer.h +++ b/core/loops/timer.h @@ -36,7 +36,6 @@ #include #include -namespace trantor { using TimerId = uint64_t; using TimePoint = std::chrono::steady_clock::time_point; using TimeInterval = std::chrono::microseconds; @@ -82,4 +81,3 @@ private: static std::atomic timersCreated_; }; -} // namespace trantor diff --git a/core/loops/timer_queue.cpp b/core/loops/timer_queue.cpp index c634de4..0eda53f 100644 --- a/core/loops/timer_queue.cpp +++ b/core/loops/timer_queue.cpp @@ -41,7 +41,6 @@ #include #endif -using namespace trantor; #ifdef __linux__ static int createTimerfd() { int timerfd = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC); diff --git a/core/loops/timer_queue.h b/core/loops/timer_queue.h index d026923..3c73878 100644 --- a/core/loops/timer_queue.h +++ b/core/loops/timer_queue.h @@ -37,7 +37,6 @@ #include #include -namespace trantor { // class Timer; class EventLoop; class Channel; @@ -92,4 +91,3 @@ protected: private: std::unordered_set timerIdSet_; }; -} // namespace trantor diff --git a/core/loops/timing_wheel.cpp b/core/loops/timing_wheel.cpp index d06f582..75266cf 100644 --- a/core/loops/timing_wheel.cpp +++ b/core/loops/timing_wheel.cpp @@ -30,9 +30,8 @@ #include "core/loops/timing_wheel.h" -using namespace trantor; -TimingWheel::TimingWheel(trantor::EventLoop *loop, +TimingWheel::TimingWheel(EventLoop *loop, size_t maxTimeout, float ticksInterval, size_t bucketsNumPerWheel) : diff --git a/core/loops/timing_wheel.h b/core/loops/timing_wheel.h index da27b36..4d84176 100644 --- a/core/loops/timing_wheel.h +++ b/core/loops/timing_wheel.h @@ -45,8 +45,6 @@ #define TIMING_BUCKET_NUM_PER_WHEEL 100 #define TIMING_TICK_INTERVAL 1.0 -namespace trantor -{ using EntryPtr = std::shared_ptr; using EntryBucket = std::unordered_set; @@ -88,7 +86,7 @@ class TimingWheel * @example Four wheels with 200 buckets per wheel means the timing wheel * can work with a timeout up to 200^4 seconds, about 50 years; */ - TimingWheel(trantor::EventLoop *loop, + TimingWheel(EventLoop *loop, size_t maxTimeout, float ticksInterval = TIMING_TICK_INTERVAL, size_t bucketsNumPerWheel = TIMING_BUCKET_NUM_PER_WHEEL); @@ -109,11 +107,10 @@ class TimingWheel std::atomic ticksCounter_{0}; - trantor::TimerId timerId_; - trantor::EventLoop *loop_; + TimerId timerId_; + EventLoop *loop_; float ticksInterval_; size_t wheelsNum_; size_t bucketsNumPerWheel_; }; -} // namespace trantor diff --git a/core/math/date.cpp b/core/math/date.cpp index ddadf8c..70e7cc6 100644 --- a/core/math/date.cpp +++ b/core/math/date.cpp @@ -41,7 +41,6 @@ #include #endif -namespace trantor { #ifdef _WIN32 int gettimeofday(timeval *tp, void *tzp) { time_t clock; @@ -295,7 +294,7 @@ Date Date::fromDbStringLocal(const std::string &datetime) { } } return std::move( - trantor::Date(year, month, day, hour, minute, second, microSecond)); + Date(year, month, day, hour, minute, second, microSecond)); } std::string Date::toCustomedFormattedStringLocal(const std::string &fmtStr, bool showMicroseconds) const { @@ -337,5 +336,3 @@ Date::Date(unsigned int year, epoch = mktime(&tm); microSecondsSinceEpoch_ = epoch * MICRO_SECONDS_PRE_SEC + microSecond; } - -} // namespace trantor diff --git a/core/math/date.h b/core/math/date.h index ee1baef..f99a01c 100644 --- a/core/math/date.h +++ b/core/math/date.h @@ -35,8 +35,6 @@ #define MICRO_SECONDS_PRE_SEC 1000000 -namespace trantor -{ /** * @brief This class represents a time point. * @@ -293,4 +291,3 @@ class Date private: int64_t microSecondsSinceEpoch_{0}; }; -} // namespace trantor diff --git a/core/math/math.h b/core/math/math.h index 9be0956..57359f3 100644 --- a/core/math/math.h +++ b/core/math/math.h @@ -324,7 +324,7 @@ public: return hf; } - // Taken from trantor (MIT License) - Funcs.h + // Taken from Trantor (BSD-style License) - Funcs.h // Copyright (c) 2018 An Tao static _ALWAYS_INLINE_ uint64_t hton64(uint64_t n) { static const int one = 1; @@ -336,7 +336,7 @@ public: return n; } - // Taken from trantor (MIT License) - Funcs.h + // Taken from Trantor (BSD-style License) - Funcs.h // Copyright (c) 2018 An Tao static _ALWAYS_INLINE_ uint64_t ntoh64(uint64_t n) { return hton64(n); diff --git a/core/net/connections/tcp_connection_impl.cpp b/core/net/connections/tcp_connection_impl.cpp index 565ddd1..b39c35b 100644 --- a/core/net/connections/tcp_connection_impl.cpp +++ b/core/net/connections/tcp_connection_impl.cpp @@ -54,10 +54,7 @@ #endif #include -using namespace trantor; - #ifdef USE_OPENSSL -namespace trantor { namespace internal { #ifdef _WIN32 // Code yanked from stackoverflow @@ -316,9 +313,9 @@ std::shared_ptr newSSLServerContext( } return ctx; } -} // namespace trantor + #else -namespace trantor { + std::shared_ptr newSSLServerContext( const std::string &certPath, const std::string &keyPath, @@ -327,7 +324,7 @@ std::shared_ptr newSSLServerContext( LOG_FATAL << "OpenSSL is not found in your system!"; abort(); } -} // namespace trantor + #endif TcpConnectionImpl::TcpConnectionImpl(EventLoop *loop, diff --git a/core/net/connections/tcp_connection_impl.h b/core/net/connections/tcp_connection_impl.h index c5aef49..7bccab2 100644 --- a/core/net/connections/tcp_connection_impl.h +++ b/core/net/connections/tcp_connection_impl.h @@ -40,8 +40,7 @@ #include #include -namespace trantor -{ + #ifdef USE_OPENSSL enum class SSLStatus { @@ -77,7 +76,7 @@ class TcpConnectionImpl : public TcpConnection, { friend class TcpServer; friend class TcpClient; - friend void trantor::removeConnection(EventLoop *loop, + friend void removeConnection(EventLoop *loop, const TcpConnectionPtr &conn); protected: @@ -363,5 +362,3 @@ protected: }; using TcpConnectionImplPtr = std::shared_ptr; - -} // namespace trantor diff --git a/core/net/connector.cpp b/core/net/connector.cpp index 6ced0dc..8337808 100644 --- a/core/net/connector.cpp +++ b/core/net/connector.cpp @@ -32,8 +32,6 @@ #include "core/loops/channel.h" #include "core/net/socket.h" -using namespace trantor; - Connector::Connector(EventLoop *loop, const InetAddress &addr, bool retry) : loop_(loop), serverAddr_(addr), retry_(retry) { } diff --git a/core/net/connector.h b/core/net/connector.h index 4b5f86b..a2e7358 100644 --- a/core/net/connector.h +++ b/core/net/connector.h @@ -35,7 +35,6 @@ #include #include -namespace trantor { class Connector : public std::enable_shared_from_this { protected: Connector(const Connector &) = delete; @@ -98,5 +97,3 @@ private: void handleError(); void retry(int sockfd); }; - -} // namespace trantor diff --git a/core/net/inet_address.cpp b/core/net/inet_address.cpp index 0f9bdd6..6c56e7a 100644 --- a/core/net/inet_address.cpp +++ b/core/net/inet_address.cpp @@ -71,7 +71,6 @@ static const in_addr_t kInaddrLoopback = INADDR_LOOPBACK; // uint32_t sin6_scope_id; /* IPv6 scope-id */ // }; -using namespace trantor; /* #ifdef __linux__ diff --git a/core/net/inet_address.h b/core/net/inet_address.h index 885385d..b392266 100644 --- a/core/net/inet_address.h +++ b/core/net/inet_address.h @@ -46,8 +46,6 @@ using uint16_t = unsigned short; #include #include -namespace trantor -{ /** * @brief Wrapper of sockaddr_in. This is an POD interface class. * @@ -231,6 +229,4 @@ class InetAddress bool isUnspecified_{true}; }; -} // namespace trantor - #endif // MUDUO_NET_INETADDRESS_H diff --git a/core/net/resolver.h b/core/net/resolver.h index 6ab0588..7ae58c1 100644 --- a/core/net/resolver.h +++ b/core/net/resolver.h @@ -34,8 +34,6 @@ #include "core/loops/event_loop.h" #include "core/net/inet_address.h" -namespace trantor -{ /** * @brief This class represents an asynchronous DNS resolver. * @note Although the c-ares library is not essential, it is recommended to @@ -44,7 +42,7 @@ namespace trantor class Resolver { public: - using Callback = std::function; + using Callback = std::function; /** * @brief Create a new DNS resolver. @@ -77,4 +75,3 @@ class Resolver */ static bool isCAresUsed(); }; -} // namespace trantor \ No newline at end of file diff --git a/core/net/resolvers/ares_resolver.cpp b/core/net/resolvers/ares_resolver.cpp index cbd0834..8988d86 100644 --- a/core/net/resolvers/ares_resolver.cpp +++ b/core/net/resolvers/ares_resolver.cpp @@ -42,10 +42,8 @@ #include #include -using namespace trantor; using namespace std::placeholders; -namespace { double getSeconds(struct timeval *tv) { if (tv) return double(tv->tv_sec) + double(tv->tv_usec) / 1000000.0; @@ -62,8 +60,6 @@ const char *getSocketType(int type) { return "Unknown"; } -} // namespace - bool Resolver::isCAresUsed() { return true; } @@ -77,7 +73,7 @@ AresResolver::LibraryInitializer::~LibraryInitializer() { AresResolver::LibraryInitializer AresResolver::libraryInitializer_; -std::shared_ptr Resolver::newResolver(trantor::EventLoop *loop, +std::shared_ptr Resolver::newResolver(EventLoop *loop, size_t timeout) { return std::make_shared(loop, timeout); } @@ -122,7 +118,7 @@ void AresResolver::resolveInLoop(const std::string &hostname, loop_->assertInLoopThread(); #ifdef _WIN32 if (hostname == "localhost") { - const static trantor::InetAddress localhost_{ "127.0.0.1", 0 }; + const static InetAddress localhost_{ "127.0.0.1", 0 }; cb(localhost_); return; } @@ -182,7 +178,7 @@ void AresResolver::onQueryResult(int status, std::lock_guard lock(globalMutex()); auto &addrItem = globalCache()[hostname]; addrItem.first = addr.sin_addr; - addrItem.second = trantor::Date::date(); + addrItem.second = Date::date(); } callback(inet); } diff --git a/core/net/resolvers/ares_resolver.h b/core/net/resolvers/ares_resolver.h index 5b4f91f..9b0cbc3 100644 --- a/core/net/resolvers/ares_resolver.h +++ b/core/net/resolvers/ares_resolver.h @@ -41,7 +41,7 @@ struct hostent; struct ares_channeldata; using ares_channel = struct ares_channeldata *; } -namespace trantor { + class AresResolver : public Resolver, public std::enable_shared_from_this { protected: @@ -52,7 +52,7 @@ protected: AresResolver &operator=(AresResolver &&) noexcept(true) = default; public: - AresResolver(trantor::EventLoop *loop, size_t timeout); + AresResolver(EventLoop *loop, size_t timeout); ~AresResolver(); virtual void resolve(const std::string &hostname, @@ -65,7 +65,7 @@ public: if (iter != globalCache().end()) { auto &cachedAddr = iter->second; if (timeout_ == 0 || - cachedAddr.second.after(timeout_) > trantor::Date::date()) { + cachedAddr.second.after(timeout_) > Date::date()) { struct sockaddr_in addr; memset(&addr, 0, sizeof addr); addr.sin_family = AF_INET; @@ -102,16 +102,16 @@ private: }; void resolveInLoop(const std::string &hostname, const Callback &cb); void init(); - trantor::EventLoop *loop_; + EventLoop *loop_; ares_channel ctx_{ nullptr }; bool timerActive_{ false }; - using ChannelList = std::map >; + using ChannelList = std::map >; ChannelList channels_; static std::unordered_map > & + std::pair > & globalCache() { static std::unordered_map > + std::pair > dnsCache; return dnsCache; } @@ -158,4 +158,3 @@ private: }; static LibraryInitializer libraryInitializer_; }; -} // namespace trantor diff --git a/core/net/resolvers/normal_resolver.cpp b/core/net/resolvers/normal_resolver.cpp index a06b3bc..40afd92 100644 --- a/core/net/resolvers/normal_resolver.cpp +++ b/core/net/resolvers/normal_resolver.cpp @@ -40,9 +40,7 @@ #include #endif -using namespace trantor; - -std::shared_ptr Resolver::newResolver(trantor::EventLoop *, +std::shared_ptr Resolver::newResolver(EventLoop *, size_t timeout) { return std::make_shared(timeout); } @@ -57,7 +55,7 @@ void NormalResolver::resolve(const std::string &hostname, if (iter != globalCache().end()) { auto &cachedAddr = iter->second; if (timeout_ == 0 || cachedAddr.second.after(static_cast( - timeout_)) > trantor::Date::date()) { + timeout_)) > Date::date()) { callback(cachedAddr.first); return; } @@ -73,7 +71,7 @@ void NormalResolver::resolve(const std::string &hostname, auto &cachedAddr = iter->second; if (thisPtr->timeout_ == 0 || cachedAddr.second.after(static_cast( - thisPtr->timeout_)) > trantor::Date::date()) { + thisPtr->timeout_)) > Date::date()) { callback(cachedAddr.first); return; } @@ -107,7 +105,7 @@ void NormalResolver::resolve(const std::string &hostname, std::lock_guard guard(thisPtr->globalMutex()); auto &addrItem = thisPtr->globalCache()[hostname]; addrItem.first = inet; - addrItem.second = trantor::Date::date(); + addrItem.second = Date::date(); } return; }); diff --git a/core/net/resolvers/normal_resolver.h b/core/net/resolvers/normal_resolver.h index cf46dc0..e6909cc 100644 --- a/core/net/resolvers/normal_resolver.h +++ b/core/net/resolvers/normal_resolver.h @@ -35,8 +35,8 @@ #include #include -namespace trantor { constexpr size_t kResolveBufferLength{ 16 * 1024 }; + class NormalResolver : public Resolver, public std::enable_shared_from_this { protected: @@ -57,11 +57,11 @@ public: private: static std::unordered_map > & + std::pair > & globalCache() { static std::unordered_map< std::string, - std::pair > + std::pair > dnsCache_; return dnsCache_; } @@ -69,8 +69,8 @@ private: static std::mutex mutex_; return mutex_; } - static trantor::ConcurrentTaskQueue &concurrentTaskQueue() { - static trantor::ConcurrentTaskQueue queue( + static ConcurrentTaskQueue &concurrentTaskQueue() { + static ConcurrentTaskQueue queue( std::thread::hardware_concurrency() < 8 ? 8 : std::thread::hardware_concurrency(), "Dns Queue"); return queue; @@ -78,4 +78,3 @@ private: const size_t timeout_; std::vector resolveBuffer_; }; -} // namespace trantor \ No newline at end of file diff --git a/core/net/socket.cpp b/core/net/socket.cpp index d47c704..f44225f 100644 --- a/core/net/socket.cpp +++ b/core/net/socket.cpp @@ -39,7 +39,6 @@ #include #endif -using namespace trantor; bool Socket::isSelfConnect(int sockfd) { struct sockaddr_in6 localaddr = getLocalAddr(sockfd); diff --git a/core/net/socket.h b/core/net/socket.h index f1e48ab..70d6b82 100644 --- a/core/net/socket.h +++ b/core/net/socket.h @@ -40,7 +40,6 @@ #endif #include -namespace trantor { class Socket { protected: @@ -167,5 +166,3 @@ public: #endif } }; - -} // namespace trantor diff --git a/core/net/tcp_client.cpp b/core/net/tcp_client.cpp index 157a230..2df6fc2 100644 --- a/core/net/tcp_client.cpp +++ b/core/net/tcp_client.cpp @@ -32,9 +32,9 @@ #include "core/net/tcp_client.h" #include "connector.h" -#include "core/net/connections/tcp_connection_impl.h" -#include "core/loops/event_loop.h" #include "core/log/logger.h" +#include "core/loops/event_loop.h" +#include "core/net/connections/tcp_connection_impl.h" #include #include @@ -43,10 +43,8 @@ #include // snprintf -using namespace trantor; using namespace std::placeholders; -namespace trantor { // void removeConnector(const ConnectorPtr &) // { // // connector-> @@ -67,8 +65,6 @@ static void defaultMessageCallback(const TcpConnectionPtr &, MsgBuffer *buf) { buf->retrieveAll(); } -} // namespace trantor - TcpClient::TcpClient(EventLoop *loop, const InetAddress &serverAddr, const std::string &nameArg) : diff --git a/core/net/tcp_client.h b/core/net/tcp_client.h index 0deafd9..23dbd32 100644 --- a/core/net/tcp_client.h +++ b/core/net/tcp_client.h @@ -39,7 +39,6 @@ #include #include -namespace trantor { class Connector; using ConnectorPtr = std::shared_ptr; class SSLContext; @@ -246,5 +245,3 @@ private: static IgnoreSigPipe initObj; #endif }; - -} // namespace trantor diff --git a/core/net/tcp_connection.h b/core/net/tcp_connection.h index 4643a6c..ee9e959 100644 --- a/core/net/tcp_connection.h +++ b/core/net/tcp_connection.h @@ -38,7 +38,6 @@ #include #include -namespace trantor { class SSLContext; std::shared_ptr newSSLServerContext( const std::string &certPath, @@ -265,4 +264,3 @@ private: std::shared_ptr contextPtr_; }; -} // namespace trantor diff --git a/core/net/tcp_server.cpp b/core/net/tcp_server.cpp index 074a34f..f03d347 100644 --- a/core/net/tcp_server.cpp +++ b/core/net/tcp_server.cpp @@ -34,7 +34,7 @@ #include "core/log/logger.h" #include #include -using namespace trantor; + using namespace std::placeholders; TcpServer::TcpServer(EventLoop *loop, @@ -175,7 +175,7 @@ const std::string TcpServer::ipPort() const { return acceptorPtr_->addr().toIpPort(); } -const trantor::InetAddress &TcpServer::address() const { +const InetAddress &TcpServer::address() const { return acceptorPtr_->addr(); } diff --git a/core/net/tcp_server.h b/core/net/tcp_server.h index 3cb8a97..5cf27c7 100644 --- a/core/net/tcp_server.h +++ b/core/net/tcp_server.h @@ -41,7 +41,6 @@ #include #include -namespace trantor { class Acceptor; class SSLContext; /** @@ -169,9 +168,9 @@ public: /** * @brief Get the address of the server. * - * @return const trantor::InetAddress& + * @return const InetAddress& */ - const trantor::InetAddress &address() const; + const InetAddress &address() const; /** * @brief Get the event loop of the server. @@ -253,5 +252,3 @@ private: // OpenSSL SSL context Object; std::shared_ptr sslCtxPtr_; }; - -} // namespace trantor diff --git a/tests/tests/AsyncFileLoggerTest.cc b/tests/tests/AsyncFileLoggerTest.cc index 6cdef0b..7d503e1 100644 --- a/tests/tests/AsyncFileLoggerTest.cc +++ b/tests/tests/AsyncFileLoggerTest.cc @@ -4,10 +4,10 @@ #include int main() { - trantor::AsyncFileLogger asyncFileLogger; + AsyncFileLogger asyncFileLogger; asyncFileLogger.setFileName("async_test"); asyncFileLogger.startLogging(); - trantor::Logger::setOutputFunction( + Logger::setOutputFunction( [&](const char *msg, const uint64_t len) { asyncFileLogger.output(msg, len); }, diff --git a/tests/tests/AsyncFileLoggerTest1.cc b/tests/tests/AsyncFileLoggerTest1.cc index 656b7d9..984bf64 100644 --- a/tests/tests/AsyncFileLoggerTest1.cc +++ b/tests/tests/AsyncFileLoggerTest1.cc @@ -7,10 +7,10 @@ using namespace std::chrono_literals; int main() { - trantor::AsyncFileLogger asyncFileLogger; + AsyncFileLogger asyncFileLogger; asyncFileLogger.setFileName("async_test"); asyncFileLogger.startLogging(); - trantor::Logger::setOutputFunction( + Logger::setOutputFunction( [&](const char *msg, const uint64_t len) { asyncFileLogger.output(msg, len); }, diff --git a/tests/tests/ConcurrentTaskQueueTest.cc b/tests/tests/ConcurrentTaskQueueTest.cc index 8f5fd36..0af5895 100644 --- a/tests/tests/ConcurrentTaskQueueTest.cc +++ b/tests/tests/ConcurrentTaskQueueTest.cc @@ -10,7 +10,7 @@ using namespace std::chrono_literals; int main() { - trantor::ConcurrentTaskQueue queue(5, "concurrT"); + ConcurrentTaskQueue queue(5, "concurrT"); std::atomic_int sum; sum = 0; for (int i = 0; i < 4; ++i) diff --git a/tests/tests/DelayedSSLClientTest.cc b/tests/tests/DelayedSSLClientTest.cc index ef463c6..950e56e 100644 --- a/tests/tests/DelayedSSLClientTest.cc +++ b/tests/tests/DelayedSSLClientTest.cc @@ -4,11 +4,11 @@ #include #include #include -using namespace trantor; + #define USE_IPV6 0 int main() { - trantor::Logger::setLogLevel(trantor::Logger::kTrace); + Logger::setLogLevel(Logger::kTrace); LOG_DEBUG << "TcpClient class test!"; EventLoop loop; #if USE_IPV6 @@ -16,12 +16,12 @@ int main() #else InetAddress serverAddr("127.0.0.1", 8888); #endif - std::shared_ptr client[10]; + std::shared_ptr client[10]; std::atomic_int connCount; connCount = 10; for (int i = 0; i < 10; ++i) { - client[i] = std::make_shared(&loop, + client[i] = std::make_shared(&loop, serverAddr, "tcpclienttest"); client[i]->setConnectionCallback( diff --git a/tests/tests/DelayedSSLServerTest.cc b/tests/tests/DelayedSSLServerTest.cc index 72dca02..e8bc074 100644 --- a/tests/tests/DelayedSSLServerTest.cc +++ b/tests/tests/DelayedSSLServerTest.cc @@ -3,7 +3,7 @@ #include "core/loops/event_loop_thread.h" #include #include -using namespace trantor; + #define USE_IPV6 0 int main() { diff --git a/tests/tests/DnsTest.cc b/tests/tests/DnsTest.cc index 9f6bccc..af28cdf 100644 --- a/tests/tests/DnsTest.cc +++ b/tests/tests/DnsTest.cc @@ -1,38 +1,38 @@ #include "core/net/resolver.h" #include -void dns(const std::shared_ptr &resolver) +void dns(const std::shared_ptr &resolver) { - auto now = trantor::Date::now(); - resolver->resolve("www.baidu.com", [now](const trantor::InetAddress &addr) { - auto interval = trantor::Date::now().microSecondsSinceEpoch() - + auto now = Date::now(); + resolver->resolve("www.baidu.com", [now](const InetAddress &addr) { + auto interval = Date::now().microSecondsSinceEpoch() - now.microSecondsSinceEpoch(); std::cout << "baidu:" << addr.toIp() << " " << interval / 1000 << "ms" << std::endl; }); resolver->resolve("www.google.com", - [now](const trantor::InetAddress &addr) { + [now](const InetAddress &addr) { auto interval = - trantor::Date::now().microSecondsSinceEpoch() - + Date::now().microSecondsSinceEpoch() - now.microSecondsSinceEpoch(); std::cout << "google:" << addr.toIp() << " " << interval / 1000 << "ms" << std::endl; }); - resolver->resolve("www.sina.com", [now](const trantor::InetAddress &addr) { - auto interval = trantor::Date::now().microSecondsSinceEpoch() - + resolver->resolve("www.sina.com", [now](const InetAddress &addr) { + auto interval = Date::now().microSecondsSinceEpoch() - now.microSecondsSinceEpoch(); std::cout << "sina:" << addr.toIp() << " " << interval / 1000 << "ms" << std::endl; }); resolver->resolve("www.xjfisfjaskfeiakdjfg.com", - [now](const trantor::InetAddress &addr) { + [now](const InetAddress &addr) { auto interval = - trantor::Date::now().microSecondsSinceEpoch() - + Date::now().microSecondsSinceEpoch() - now.microSecondsSinceEpoch(); std::cout << "bad address:" << addr.toIp() << " " << interval / 1000 << "ms" << std::endl; }); - resolver->resolve("localhost", [now](const trantor::InetAddress &addr) { - auto interval = trantor::Date::now().microSecondsSinceEpoch() - + resolver->resolve("localhost", [now](const InetAddress &addr) { + auto interval = Date::now().microSecondsSinceEpoch() - now.microSecondsSinceEpoch(); std::cout << "localhost:" << addr.toIp() << " " << interval / 1000 << "ms" << std::endl; @@ -40,8 +40,8 @@ void dns(const std::shared_ptr &resolver) } int main() { - trantor::EventLoop loop; - auto resolver = trantor::Resolver::newResolver(&loop); + EventLoop loop; + auto resolver = Resolver::newResolver(&loop); dns(resolver); loop.runAfter(1.0, [resolver]() { dns(resolver); }); loop.loop(); diff --git a/tests/tests/KickoffTest.cc b/tests/tests/KickoffTest.cc index b957ce7..a11b091 100644 --- a/tests/tests/KickoffTest.cc +++ b/tests/tests/KickoffTest.cc @@ -3,7 +3,7 @@ #include "core/loops/event_loop_thread.h" #include #include -using namespace trantor; + #define USE_IPV6 0 int main() { diff --git a/tests/tests/LoggerTest.cc b/tests/tests/LoggerTest.cc index c53b706..fc090f7 100644 --- a/tests/tests/LoggerTest.cc +++ b/tests/tests/LoggerTest.cc @@ -8,7 +8,7 @@ int main() LOG_DEBUG << (const char)'8'; LOG_DEBUG << &i; LOG_DEBUG << (long double)3.1415; - LOG_DEBUG << trantor::Fmt("%.3g", 3.1415926); + LOG_DEBUG << Fmt("%.3g", 3.1415926); LOG_DEBUG << "debug log!" << 1; LOG_TRACE << "trace log!" << 2; LOG_INFO << "info log!" << 3; diff --git a/tests/tests/RunInLoopTest1.cc b/tests/tests/RunInLoopTest1.cc index e2555f4..ab4b397 100644 --- a/tests/tests/RunInLoopTest1.cc +++ b/tests/tests/RunInLoopTest1.cc @@ -13,7 +13,7 @@ using namespace std::chrono_literals; int main() { - trantor::EventLoop loop; + EventLoop loop; std::thread thread([&loop]() { std::this_thread::sleep_for(3s); loop.runInLoop([&loop]() { diff --git a/tests/tests/RunInLoopTest2.cc b/tests/tests/RunInLoopTest2.cc index 2ae1f66..ed0c1b7 100644 --- a/tests/tests/RunInLoopTest2.cc +++ b/tests/tests/RunInLoopTest2.cc @@ -12,7 +12,7 @@ int main() counter = 0; std::promise pro; auto ft = pro.get_future(); - trantor::EventLoopThread loopThread; + EventLoopThread loopThread; auto loop = loopThread.getLoop(); loop->runInLoop([&counter, &pro, loop]() { diff --git a/tests/tests/RunOnQuitTest.cc b/tests/tests/RunOnQuitTest.cc index 4ffd5ac..a7223f2 100644 --- a/tests/tests/RunOnQuitTest.cc +++ b/tests/tests/RunOnQuitTest.cc @@ -10,7 +10,7 @@ int main() { std::atomic flag(false); { - trantor::EventLoopThread thr; + EventLoopThread thr; thr.getLoop()->runOnQuit([&]() { flag = true; }); thr.run(); thr.getLoop()->quit(); diff --git a/tests/tests/SSLClientTest.cc b/tests/tests/SSLClientTest.cc index 7c6ffa5..320e490 100644 --- a/tests/tests/SSLClientTest.cc +++ b/tests/tests/SSLClientTest.cc @@ -4,11 +4,11 @@ #include #include #include -using namespace trantor; + #define USE_IPV6 0 int main() { - trantor::Logger::setLogLevel(trantor::Logger::kTrace); + Logger::setLogLevel(Logger::kTrace); LOG_DEBUG << "TcpClient class test!"; EventLoop loop; #if USE_IPV6 @@ -16,12 +16,12 @@ int main() #else InetAddress serverAddr("127.0.0.1", 8888); #endif - std::shared_ptr client[10]; + std::shared_ptr client[10]; std::atomic_int connCount; connCount = 1; for (int i = 0; i < connCount; ++i) { - client[i] = std::make_shared(&loop, + client[i] = std::make_shared(&loop, serverAddr, "tcpclienttest"); client[i]->enableSSL(false, false); diff --git a/tests/tests/SSLServerTest.cc b/tests/tests/SSLServerTest.cc index cc231d4..8bbbd5f 100644 --- a/tests/tests/SSLServerTest.cc +++ b/tests/tests/SSLServerTest.cc @@ -3,7 +3,7 @@ #include "core/loops/event_loop_thread.h" #include #include -using namespace trantor; + #define USE_IPV6 0 int main() { diff --git a/tests/tests/SendfileTest.cc b/tests/tests/SendfileTest.cc index 310e37a..af3a0ac 100644 --- a/tests/tests/SendfileTest.cc +++ b/tests/tests/SendfileTest.cc @@ -10,7 +10,7 @@ #include #endif -using namespace trantor; + #define USE_IPV6 0 int main(int argc, char *argv[]) { diff --git a/tests/tests/SerialTaskQueueTest1.cc b/tests/tests/SerialTaskQueueTest1.cc index a2cb591..3245a9d 100755 --- a/tests/tests/SerialTaskQueueTest1.cc +++ b/tests/tests/SerialTaskQueueTest1.cc @@ -7,9 +7,9 @@ using namespace std::chrono_literals; int main() { - trantor::Logger::setLogLevel(trantor::Logger::kTrace); - trantor::SerialTaskQueue queue1("test queue1"); - trantor::SerialTaskQueue queue2(""); + Logger::setLogLevel(Logger::kTrace); + SerialTaskQueue queue1("test queue1"); + SerialTaskQueue queue2(""); queue1.runTaskInQueue([&]() { for (int i = 0; i < 5; ++i) { diff --git a/tests/tests/SerialTaskQueueTest2.cc b/tests/tests/SerialTaskQueueTest2.cc index 59068fe..3fb3d9d 100644 --- a/tests/tests/SerialTaskQueueTest2.cc +++ b/tests/tests/SerialTaskQueueTest2.cc @@ -12,7 +12,7 @@ int main() counter = 0; std::promise pro; auto ft = pro.get_future(); - trantor::SerialTaskQueue queue(""); + SerialTaskQueue queue(""); queue.runTaskInQueue([&counter, &pro, &queue]() { for (int i = 0; i < 10000; ++i) { diff --git a/tests/tests/TcpClientTest.cc b/tests/tests/TcpClientTest.cc index 3bd0051..dfb78e7 100644 --- a/tests/tests/TcpClientTest.cc +++ b/tests/tests/TcpClientTest.cc @@ -4,11 +4,11 @@ #include #include #include -using namespace trantor; + #define USE_IPV6 0 int main() { - trantor::Logger::setLogLevel(trantor::Logger::kTrace); + Logger::setLogLevel(Logger::kTrace); LOG_DEBUG << "TcpClient class test!"; EventLoop loop; #if USE_IPV6 @@ -16,12 +16,12 @@ int main() #else InetAddress serverAddr("127.0.0.1", 8888); #endif - std::shared_ptr client[10]; + std::shared_ptr client[10]; std::atomic_int connCount; connCount = 10; for (int i = 0; i < 10; ++i) { - client[i] = std::make_shared(&loop, + client[i] = std::make_shared(&loop, serverAddr, "tcpclienttest"); client[i]->setConnectionCallback( diff --git a/tests/tests/TcpServerTest.cc b/tests/tests/TcpServerTest.cc index 5fc526b..1c19dcb 100644 --- a/tests/tests/TcpServerTest.cc +++ b/tests/tests/TcpServerTest.cc @@ -3,7 +3,7 @@ #include "core/loops/event_loop_thread.h" #include #include -using namespace trantor; + #define USE_IPV6 0 int main() { diff --git a/tests/tests/TimerTest.cc b/tests/tests/TimerTest.cc index 5d832a0..05ae0a4 100644 --- a/tests/tests/TimerTest.cc +++ b/tests/tests/TimerTest.cc @@ -7,8 +7,8 @@ using namespace std::literals; int main() { - trantor::Logger::setLogLevel(trantor::Logger::kTrace); - trantor::EventLoop loop; + Logger::setLogLevel(Logger::kTrace); + EventLoop loop; auto id1 = loop.runAfter(1s, []() { LOG_ERROR << "This info shouldn't be displayed!"; }); @@ -22,7 +22,7 @@ int main() }); thread.detach(); loop.runEvery(3, []() { LOG_DEBUG << " runEvery 3s"; }); - loop.runAt(trantor::Date::date().after(10), + loop.runAt(Date::date().after(10), []() { LOG_DEBUG << "runAt 10s later"; }); loop.runAfter(5, []() { std::cout << "runAt 5s later" << std::endl; }); loop.runEvery(1, []() { std::cout << "runEvery 1s" << std::endl; }); diff --git a/tests/tests/TimerTest1.cc b/tests/tests/TimerTest1.cc index 9474a3e..87e9a83 100644 --- a/tests/tests/TimerTest1.cc +++ b/tests/tests/TimerTest1.cc @@ -3,9 +3,9 @@ #include int main() { - trantor::EventLoop loop; - LOG_FATAL << trantor::Date::date().roundDay().microSecondsSinceEpoch(); - trantor::Date begin = trantor::Date::date().roundSecond().after(2); + EventLoop loop; + LOG_FATAL << Date::date().roundDay().microSecondsSinceEpoch(); + Date begin = Date::date().roundSecond().after(2); auto id = loop.runAt(begin, [begin, &loop]() { LOG_DEBUG << "test begin:"; srand((unsigned int)time(NULL)); diff --git a/tests/tests/TimingWheelTest.cc b/tests/tests/TimingWheelTest.cc index 96fdc26..1063439 100644 --- a/tests/tests/TimingWheelTest.cc +++ b/tests/tests/TimingWheelTest.cc @@ -26,9 +26,9 @@ MyClass::~MyClass() int main() { LOG_DEBUG << "start"; - trantor::EventLoop loop; + EventLoop loop; std::weak_ptr weakEntry; - trantor::TimingWheel wheel(&loop, 75, 0.1, 100); + TimingWheel wheel(&loop, 75, 0.1, 100); { auto entry = std::shared_ptr(new MyClass); diff --git a/tests/unittests/DateUnittest.cc b/tests/unittests/DateUnittest.cc index e3aaafb..61f9d23 100644 --- a/tests/unittests/DateUnittest.cc +++ b/tests/unittests/DateUnittest.cc @@ -2,37 +2,37 @@ #include #include #include -using namespace trantor; + TEST(Date, constructorTest) { EXPECT_STREQ("1985-01-01 00:00:00", - trantor::Date(1985, 1, 1) + Date(1985, 1, 1) .toCustomedFormattedStringLocal("%Y-%m-%d %H:%M:%S") .c_str()); EXPECT_STREQ("2004-02-29 00:00:00.000000", - trantor::Date(2004, 2, 29) + Date(2004, 2, 29) .toCustomedFormattedStringLocal("%Y-%m-%d %H:%M:%S", true) .c_str()); EXPECT_STRNE("2001-02-29 00:00:00.000000", - trantor::Date(2001, 2, 29) + Date(2001, 2, 29) .toCustomedFormattedStringLocal("%Y-%m-%d %H:%M:%S", true) .c_str()); EXPECT_STREQ("2018-01-01 00:00:00.000000", - trantor::Date(2018, 1, 1, 12, 12, 12, 2321) + Date(2018, 1, 1, 12, 12, 12, 2321) .roundDay() .toCustomedFormattedStringLocal("%Y-%m-%d %H:%M:%S", true) .c_str()); } TEST(Date, DatabaseStringTest) { - auto now = trantor::Date::now(); - EXPECT_EQ(now, trantor::Date::fromDbStringLocal(now.toDbStringLocal())); + auto now = Date::now(); + EXPECT_EQ(now, Date::fromDbStringLocal(now.toDbStringLocal())); std::string dbString = "2018-01-01 00:00:00.123"; - auto dbDate = trantor::Date::fromDbStringLocal(dbString); + auto dbDate = Date::fromDbStringLocal(dbString); auto ms = (dbDate.microSecondsSinceEpoch() % 1000000) / 1000; EXPECT_EQ(ms, 123); dbString = "2018-01-01 00:00:00"; - dbDate = trantor::Date::fromDbStringLocal(dbString); + dbDate = Date::fromDbStringLocal(dbString); ms = (dbDate.microSecondsSinceEpoch() % 1000000) / 1000; EXPECT_EQ(ms, 0); } diff --git a/tests/unittests/InetAddressUnittest.cc b/tests/unittests/InetAddressUnittest.cc index 45b92e3..f5b5a95 100644 --- a/tests/unittests/InetAddressUnittest.cc +++ b/tests/unittests/InetAddressUnittest.cc @@ -2,7 +2,7 @@ #include #include #include -using namespace trantor; + TEST(InetAddress, innerIpTest) { EXPECT_EQ(true, InetAddress("192.168.0.1", 0).isIntranetIp()); diff --git a/tests/unittests/MsgBufferUnittest.cc b/tests/unittests/MsgBufferUnittest.cc index ff47db9..4509868 100644 --- a/tests/unittests/MsgBufferUnittest.cc +++ b/tests/unittests/MsgBufferUnittest.cc @@ -2,7 +2,7 @@ #include #include #include -using namespace trantor; + TEST(MsgBufferTest, readableTest) { MsgBuffer buffer; diff --git a/tests/unittests/splitStringUnittest.cc b/tests/unittests/splitStringUnittest.cc index 39d0191..ab4ed08 100644 --- a/tests/unittests/splitStringUnittest.cc +++ b/tests/unittests/splitStringUnittest.cc @@ -1,7 +1,7 @@ #include "core/math/date.h" #include #include -using namespace trantor; + TEST(splitString, ACCEPT_EMPTY_STRING1) { std::string originString = "1,2,3"; @@ -31,7 +31,7 @@ TEST(splitString, ACCEPT_EMPTY_STRING4) } TEST(splitString, ACCEPT_EMPTY_STRING5) { - std::string originString = "trantor::splitString"; + std::string originString = "splitString"; auto out = splitString(originString, "::", true); EXPECT_EQ(out.size(), 2); EXPECT_STREQ(out[0].data(), "trantor"); @@ -39,7 +39,7 @@ TEST(splitString, ACCEPT_EMPTY_STRING5) } TEST(splitString, ACCEPT_EMPTY_STRING6) { - std::string originString = "trantor::::splitString"; + std::string originString = "::splitString"; auto out = splitString(originString, "::", true); EXPECT_EQ(out.size(), 3); EXPECT_STREQ(out[0].data(), "trantor"); @@ -48,7 +48,7 @@ TEST(splitString, ACCEPT_EMPTY_STRING6) } TEST(splitString, ACCEPT_EMPTY_STRING7) { - std::string originString = "trantor:::splitString"; + std::string originString = ":splitString"; auto out = splitString(originString, "::", true); EXPECT_EQ(out.size(), 2); EXPECT_STREQ(out[0].data(), "trantor"); @@ -56,8 +56,8 @@ TEST(splitString, ACCEPT_EMPTY_STRING7) } TEST(splitString, ACCEPT_EMPTY_STRING8) { - std::string originString = "trantor:::splitString"; - auto out = splitString(originString, "trantor:::splitString", true); + std::string originString = ":splitString"; + auto out = splitString(originString, ":splitString", true); EXPECT_EQ(out.size(), 2); EXPECT_STREQ(out[0].data(), ""); EXPECT_STREQ(out[1].data(), ""); @@ -105,7 +105,7 @@ TEST(splitString, NO_ACCEPT_EMPTY_STRING3) } TEST(splitString, NO_ACCEPT_EMPTY_STRING4) { - std::string originString = "trantor::splitString"; + std::string originString = "splitString"; auto out = splitString(originString, "::"); EXPECT_EQ(out.size(), 2); EXPECT_STREQ(out[0].data(), "trantor"); @@ -113,7 +113,7 @@ TEST(splitString, NO_ACCEPT_EMPTY_STRING4) } TEST(splitString, NO_ACCEPT_EMPTY_STRING5) { - std::string originString = "trantor::::splitString"; + std::string originString = "::splitString"; auto out = splitString(originString, "::"); EXPECT_EQ(out.size(), 2); EXPECT_STREQ(out[0].data(), "trantor"); @@ -121,7 +121,7 @@ TEST(splitString, NO_ACCEPT_EMPTY_STRING5) } TEST(splitString, NO_ACCEPT_EMPTY_STRING6) { - std::string originString = "trantor:::splitString"; + std::string originString = ":splitString"; auto out = splitString(originString, "::"); EXPECT_EQ(out.size(), 2); EXPECT_STREQ(out[0].data(), "trantor"); @@ -129,8 +129,8 @@ TEST(splitString, NO_ACCEPT_EMPTY_STRING6) } TEST(splitString, NO_ACCEPT_EMPTY_STRING7) { - std::string originString = "trantor:::splitString"; - auto out = splitString(originString, "trantor:::splitString"); + std::string originString = ":splitString"; + auto out = splitString(originString, ":splitString"); EXPECT_EQ(out.size(), 0); } TEST(splitString, NO_ACCEPT_EMPTY_STRING8) diff --git a/web_backends/drogon/drogon/README.md b/web_backends/drogon/drogon/README.md index 9e457a8..eb6d839 100755 --- a/web_backends/drogon/drogon/README.md +++ b/web_backends/drogon/drogon/README.md @@ -51,7 +51,7 @@ using namespace drogon; int main() { app().setLogPath("./") - .setLogLevel(trantor::Logger::kWarn) + .setLogLevel(Logger::kWarn) .addListener("0.0.0.0", 80) .setThreadNum(16) .enableRunAsDaemon() diff --git a/web_backends/drogon/drogon/examples/benchmark/main.cc b/web_backends/drogon/drogon/examples/benchmark/main.cc index 5e79fc6..da5a4c6 100644 --- a/web_backends/drogon/drogon/examples/benchmark/main.cc +++ b/web_backends/drogon/drogon/examples/benchmark/main.cc @@ -4,7 +4,7 @@ using namespace drogon; int main() { app() .setLogPath("./") - .setLogLevel(trantor::Logger::kWarn) + .setLogLevel(Logger::kWarn) .addListener("0.0.0.0", 7770) .setThreadNum(0) .registerSyncAdvice([](const HttpRequestPtr &req) -> HttpResponsePtr { diff --git a/web_backends/drogon/drogon/examples/client_example/main.cc b/web_backends/drogon/drogon/examples/client_example/main.cc index 3a4bb6a..916e8a2 100644 --- a/web_backends/drogon/drogon/examples/client_example/main.cc +++ b/web_backends/drogon/drogon/examples/client_example/main.cc @@ -7,7 +7,7 @@ using namespace drogon; int nth_resp = 0; int main() { - trantor::Logger::setLogLevel(trantor::Logger::kTrace); + Logger::setLogLevel(Logger::kTrace); { auto client = HttpClient::newHttpClient("http://www.baidu.com"); auto req = HttpRequest::newHttpRequest(); diff --git a/web_backends/drogon/drogon/examples/simple_reverse_proxy/plugins/SimpleReverseProxy.cc b/web_backends/drogon/drogon/examples/simple_reverse_proxy/plugins/SimpleReverseProxy.cc index 668a44a..27198f1 100644 --- a/web_backends/drogon/drogon/examples/simple_reverse_proxy/plugins/SimpleReverseProxy.cc +++ b/web_backends/drogon/drogon/examples/simple_reverse_proxy/plugins/SimpleReverseProxy.cc @@ -64,7 +64,7 @@ void SimpleReverseProxy::preRouting(const HttpRequestPtr &req, if (!clientPtr) { auto &addr = backendAddrs_[index % backendAddrs_.size()]; clientPtr = HttpClient::newHttpClient( - addr, trantor::EventLoop::getEventLoopOfCurrentThread()); + addr, EventLoop::getEventLoopOfCurrentThread()); clientPtr->setPipeliningDepth(pipeliningDepth_); } req->setPassThrough(true); diff --git a/web_backends/drogon/drogon/examples/websocket_client/WebSocketClient.cc b/web_backends/drogon/drogon/examples/websocket_client/WebSocketClient.cc index 9ee67ff..812f1cc 100644 --- a/web_backends/drogon/drogon/examples/websocket_client/WebSocketClient.cc +++ b/web_backends/drogon/drogon/examples/websocket_client/WebSocketClient.cc @@ -68,7 +68,7 @@ int main(int argc, char *argv[]) { // Quit the application after 15 seconds app().getLoop()->runAfter(15, []() { app().quit(); }); - app().setLogLevel(trantor::Logger::kDebug); + app().setLogLevel(Logger::kDebug); app().run(); LOG_INFO << "bye!"; return 0; diff --git a/web_backends/drogon/drogon/lib/inc/drogon/HttpAppFramework.h b/web_backends/drogon/drogon/lib/inc/drogon/HttpAppFramework.h index 7756a7e..811c60a 100644 --- a/web_backends/drogon/drogon/lib/inc/drogon/HttpAppFramework.h +++ b/web_backends/drogon/drogon/lib/inc/drogon/HttpAppFramework.h @@ -59,7 +59,7 @@ using DefaultHandler = std::function &&)>; -class HttpAppFramework : public trantor::NonCopyable { +class HttpAppFramework : public NonCopyable { public: virtual ~HttpAppFramework() = default; /// Get the instance of HttpAppFramework @@ -104,7 +104,7 @@ public: * User can run some timer tasks or other tasks in this loop; * This method can be call in any thread. */ - virtual trantor::EventLoop *getLoop() const = 0; + virtual EventLoop *getLoop() const = 0; /// Get an IO loop with id. E.g. 0 <= id < #Total thread-loops /** @@ -114,7 +114,7 @@ public: * REMARKS : Function assumed the number of threads will not exceed 2^32. * Change to long long for alien computers. */ - virtual trantor::EventLoop *getIOLoop(size_t id) const = 0; + virtual EventLoop *getIOLoop(size_t id) const = 0; /// Set custom 404 page /** @@ -191,8 +191,8 @@ public: * Users can use this advice to implement some security policies. */ virtual HttpAppFramework ®isterNewConnectionAdvice( - const std::function &advice) = 0; + const std::function &advice) = 0; /** * @brief Register an advice for new HTTP responses. @@ -878,7 +878,7 @@ public: * @note * This operation can be performed by an option in the configuration file. */ - virtual HttpAppFramework &setLogLevel(trantor::Logger::LogLevel level) = 0; + virtual HttpAppFramework &setLogLevel(Logger::LogLevel level) = 0; /// Enable the sendfile system call in linux. /** @@ -1179,7 +1179,7 @@ public: * When the c-ares library is installed in the system, it runs with the best * performance. */ - virtual const std::shared_ptr &getResolver() const = 0; + virtual const std::shared_ptr &getResolver() const = 0; /// Return true is drogon supports SSL(https) virtual bool supportSSL() const = 0; @@ -1204,11 +1204,11 @@ public: /** * @brief Get the addresses of listeners. * - * @return std::vector + * @return std::vector * @note This method should be called after calling the app().run(). One * could run this method in an AOP join point (such as the BeginningAdvice). */ - virtual std::vector getListeners() const = 0; + virtual std::vector getListeners() const = 0; /** * @brief Enable ReusePort mode or not. If the mode is enabled, one can run diff --git a/web_backends/drogon/drogon/lib/inc/drogon/HttpClient.h b/web_backends/drogon/drogon/lib/inc/drogon/HttpClient.h index d765f30..b577215 100644 --- a/web_backends/drogon/drogon/lib/inc/drogon/HttpClient.h +++ b/web_backends/drogon/drogon/lib/inc/drogon/HttpClient.h @@ -42,7 +42,7 @@ using HttpClientPtr = std::shared_ptr; * response callbacks are invoked without fear of accidental deconstruction. * */ -class HttpClient : public trantor::NonCopyable { +class HttpClient : public NonCopyable { public: /** * @brief Send a request asynchronously to the server @@ -178,12 +178,12 @@ public: static HttpClientPtr newHttpClient(const std::string &ip, uint16_t port, bool useSSL = false, - trantor::EventLoop *loop = nullptr, + EventLoop *loop = nullptr, bool useOldTLS = false, bool validateCert = true); /// Get the event loop of the client; - virtual trantor::EventLoop *getLoop() = 0; + virtual EventLoop *getLoop() = 0; /// Get the number of bytes sent or received virtual size_t bytesSent() const = 0; @@ -221,7 +221,7 @@ public: * */ static HttpClientPtr newHttpClient(const std::string &hostString, - trantor::EventLoop *loop = nullptr, + EventLoop *loop = nullptr, bool useOldTLS = false, bool validateCert = true); diff --git a/web_backends/drogon/drogon/lib/inc/drogon/IOThreadStorage.h b/web_backends/drogon/drogon/lib/inc/drogon/IOThreadStorage.h index aa79662..bb4fc7b 100644 --- a/web_backends/drogon/drogon/lib/inc/drogon/IOThreadStorage.h +++ b/web_backends/drogon/drogon/lib/inc/drogon/IOThreadStorage.h @@ -56,7 +56,7 @@ namespace drogon { * @endcode */ template -class IOThreadStorage : public trantor::NonCopyable { +class IOThreadStorage : public NonCopyable { public: using ValueType = C; using InitCallback = std::function; diff --git a/web_backends/drogon/drogon/lib/inc/drogon/WebSocketClient.h b/web_backends/drogon/drogon/lib/inc/drogon/WebSocketClient.h index 0342907..a5d93cb 100644 --- a/web_backends/drogon/drogon/lib/inc/drogon/WebSocketClient.h +++ b/web_backends/drogon/drogon/lib/inc/drogon/WebSocketClient.h @@ -66,7 +66,7 @@ public: const WebSocketRequestCallback &callback) = 0; /// Get the event loop of the client; - virtual trantor::EventLoop *getLoop() = 0; + virtual EventLoop *getLoop() = 0; /** * @brief Create a websocket client using the given ip and port to connect @@ -91,7 +91,7 @@ public: const std::string &ip, uint16_t port, bool useSSL = false, - trantor::EventLoop *loop = nullptr, + EventLoop *loop = nullptr, bool useOldTLS = false, bool validateCert = true); @@ -121,7 +121,7 @@ public: */ static WebSocketClientPtr newWebSocketClient( const std::string &hostString, - trantor::EventLoop *loop = nullptr, + EventLoop *loop = nullptr, bool useOldTLS = false, bool validateCert = true); diff --git a/web_backends/drogon/drogon/lib/inc/drogon/WebSocketConnection.h b/web_backends/drogon/drogon/lib/inc/drogon/WebSocketConnection.h index bda3fe2..5ef00a8 100644 --- a/web_backends/drogon/drogon/lib/inc/drogon/WebSocketConnection.h +++ b/web_backends/drogon/drogon/lib/inc/drogon/WebSocketConnection.h @@ -111,10 +111,10 @@ public: const WebSocketMessageType type = WebSocketMessageType::Text) = 0; /// Return the local IP address and port number of the connection - virtual const trantor::InetAddress &localAddr() const = 0; + virtual const InetAddress &localAddr() const = 0; /// Return the remote IP address and port number of the connection - virtual const trantor::InetAddress &peerAddr() const = 0; + virtual const InetAddress &peerAddr() const = 0; /// Return true if the connection is open virtual bool connected() const = 0; diff --git a/web_backends/drogon/drogon/lib/inc/drogon/drogon_test.h b/web_backends/drogon/drogon/lib/inc/drogon/drogon_test.h index 08df9d6..2c764aa 100644 --- a/web_backends/drogon/drogon/lib/inc/drogon/drogon_test.h +++ b/web_backends/drogon/drogon/lib/inc/drogon/drogon_test.h @@ -318,7 +318,7 @@ inline ThreadSafeStream printErr() { return ThreadSafeStream(std::cerr); } -class CaseBase : public trantor::NonCopyable { +class CaseBase : public NonCopyable { public: CaseBase() = default; CaseBase(const std::string &name) : diff --git a/web_backends/drogon/drogon/lib/inc/drogon/plugins/AccessLogger.h b/web_backends/drogon/drogon/lib/inc/drogon/plugins/AccessLogger.h index eefe53b..6ba1090 100644 --- a/web_backends/drogon/drogon/lib/inc/drogon/plugins/AccessLogger.h +++ b/web_backends/drogon/drogon/lib/inc/drogon/plugins/AccessLogger.h @@ -84,89 +84,89 @@ public: void shutdown() override; private: - trantor::AsyncFileLogger asyncFileLogger_; + AsyncFileLogger asyncFileLogger_; int logIndex_{ 0 }; bool useLocalTime_{ true }; - using LogFunction = std::function; std::vector logFunctions_; - void logging(trantor::LogStream &stream, + void logging(LogStream &stream, const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &resp); void createLogFunctions(std::string format); LogFunction newLogFunction(const std::string &placeholder); std::map logFunctionMap_; //$request_path - static void outputReqPath(trantor::LogStream &, + static void outputReqPath(LogStream &, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &); //$request_query - static void outputReqQuery(trantor::LogStream &, + static void outputReqQuery(LogStream &, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &); //$request_url - static void outputReqURL(trantor::LogStream &, + static void outputReqURL(LogStream &, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &); //$date - void outputDate(trantor::LogStream &, + void outputDate(LogStream &, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &) const; //$request_date - void outputReqDate(trantor::LogStream &, + void outputReqDate(LogStream &, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &) const; //$remote_addr - static void outputRemoteAddr(trantor::LogStream &, + static void outputRemoteAddr(LogStream &, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &); //$local_addr - static void outputLocalAddr(trantor::LogStream &, + static void outputLocalAddr(LogStream &, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &); //$request_len $body_bytes_received - static void outputReqLength(trantor::LogStream &, + static void outputReqLength(LogStream &, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &); //$response_len $body_bytes_sent - static void outputRespLength(trantor::LogStream &, + static void outputRespLength(LogStream &, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &); //$method - static void outputMethod(trantor::LogStream &, + static void outputMethod(LogStream &, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &); //$thread - static void outputThreadNumber(trantor::LogStream &, + static void outputThreadNumber(LogStream &, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &); //$http_[header_name] - static void outputReqHeader(trantor::LogStream &stream, + static void outputReqHeader(LogStream &stream, const drogon::HttpRequestPtr &req, const std::string &headerName); //$cookie_[cookie_name] - static void outputReqCookie(trantor::LogStream &stream, + static void outputReqCookie(LogStream &stream, const drogon::HttpRequestPtr &req, const std::string &cookie); //$upstream_http_[header_name] - static void outputRespHeader(trantor::LogStream &stream, + static void outputRespHeader(LogStream &stream, const drogon::HttpResponsePtr &resp, const std::string &headerName); //$status - static void outputStatusString(trantor::LogStream &, + static void outputStatusString(LogStream &, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &); //$status_code - static void outputStatusCode(trantor::LogStream &, + static void outputStatusCode(LogStream &, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &); //$processing_time - static void outputProcessingTime(trantor::LogStream &, + static void outputProcessingTime(LogStream &, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &); //$upstream_http_content-type $upstream_http_content_type - static void outputRespContentType(trantor::LogStream &, + static void outputRespContentType(LogStream &, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &); }; diff --git a/web_backends/drogon/drogon/lib/inc/drogon/plugins/Plugin.h b/web_backends/drogon/drogon/lib/inc/drogon/plugins/Plugin.h index 39be9ca..2bbab01 100644 --- a/web_backends/drogon/drogon/lib/inc/drogon/plugins/Plugin.h +++ b/web_backends/drogon/drogon/lib/inc/drogon/plugins/Plugin.h @@ -29,7 +29,7 @@ enum class PluginStatus { * @brief The abstract base class for plugins. * */ -class PluginBase : public trantor::NonCopyable { +class PluginBase : public NonCopyable { public: /// This method must be called by drogon. void initialize() { diff --git a/web_backends/drogon/drogon/lib/inc/drogon/utils/Utilities.h b/web_backends/drogon/drogon/lib/inc/drogon/utils/Utilities.h index 6d3f3ab..df6c08a 100644 --- a/web_backends/drogon/drogon/lib/inc/drogon/utils/Utilities.h +++ b/web_backends/drogon/drogon/lib/inc/drogon/utils/Utilities.h @@ -131,13 +131,13 @@ std::string brotliDecompress(const char *data, @endcode */ char *getHttpFullDate( - const trantor::Date &date = trantor::Date::now()); + const Date &date = Date::now()); -/// Get the trantor::Date object according to the http full date string +/// Get the Date object according to the http full date string /** - * Returns trantor::Date(std::numeric_limits::max()) upon failure. + * Returns Date(std::numeric_limits::max()) upon failure. */ -trantor::Date getHttpDate(const std::string &httpFullDateString); +Date getHttpDate(const std::string &httpFullDateString); /// Get a formatted string std::string formattedString(const char *format, ...); diff --git a/web_backends/drogon/drogon/lib/inc/drogon/utils/string_view.h b/web_backends/drogon/drogon/lib/inc/drogon/utils/string_view.h index c7bd6fa..2f46786 100644 --- a/web_backends/drogon/drogon/lib/inc/drogon/utils/string_view.h +++ b/web_backends/drogon/drogon/lib/inc/drogon/utils/string_view.h @@ -29,12 +29,11 @@ using std::string_view; using boost::string_view; #endif } // namespace drogon -namespace trantor { + inline LogStream &operator<<(LogStream &ls, const drogon::string_view &v) { ls.append(v.data(), v.length()); return ls; } -} // namespace trantor #if __cplusplus < 201703L && !(defined _MSC_VER && _MSC_VER > 1900) namespace std { diff --git a/web_backends/drogon/drogon/lib/inc/http/CacheFile.h b/web_backends/drogon/drogon/lib/inc/http/CacheFile.h index c97f58a..09777e4 100644 --- a/web_backends/drogon/drogon/lib/inc/http/CacheFile.h +++ b/web_backends/drogon/drogon/lib/inc/http/CacheFile.h @@ -20,7 +20,7 @@ #include namespace drogon { -class CacheFile : public trantor::NonCopyable { +class CacheFile : public NonCopyable { public: explicit CacheFile(const std::string &path, bool autoDelete = true); ~CacheFile(); diff --git a/web_backends/drogon/drogon/lib/inc/http/CacheMap.h b/web_backends/drogon/drogon/lib/inc/http/CacheMap.h index 2582429..6188dad 100644 --- a/web_backends/drogon/drogon/lib/inc/http/CacheMap.h +++ b/web_backends/drogon/drogon/lib/inc/http/CacheMap.h @@ -79,7 +79,7 @@ public: * The max delay of the CacheMap is about * tickInterval*(bucketsNumPerWheel^wheelsNum) seconds. */ - CacheMap(trantor::EventLoop *loop, + CacheMap(EventLoop *loop, float tickInterval = TICK_INTERVAL, size_t wheelsNum = WHEELS_NUM, size_t bucketsNumPerWheel = BUCKET_NUM_PER_WHEEL) : @@ -327,9 +327,9 @@ public: /** * @brief Get the event loop object * - * @return trantor::EventLoop* + * @return EventLoop* */ - trantor::EventLoop *getLoop() { + EventLoop *getLoop() { return loop_; } @@ -377,8 +377,8 @@ private: std::mutex mtx_; std::mutex bucketMutex_; - trantor::TimerId timerId_; - trantor::EventLoop *loop_; + TimerId timerId_; + EventLoop *loop_; float tickInterval_; size_t wheelsNumber_; diff --git a/web_backends/drogon/drogon/lib/inc/http/Cookie.h b/web_backends/drogon/drogon/lib/inc/http/Cookie.h index 40a5d7c..91df80c 100644 --- a/web_backends/drogon/drogon/lib/inc/http/Cookie.h +++ b/web_backends/drogon/drogon/lib/inc/http/Cookie.h @@ -42,7 +42,7 @@ public: * * @param date The expiration date */ - void setExpiresDate(const trantor::Date &date) { + void setExpiresDate(const Date &date) { expiresDate_ = date; } @@ -114,14 +114,14 @@ public: /** * @brief Get the expiration date of the cookie */ - const trantor::Date &expiresDate() const { + const Date &expiresDate() const { return expiresDate_; } /** * @brief Get the expiration date of the cookie */ - const trantor::Date &getExpiresDate() const { + const Date &getExpiresDate() const { return expiresDate_; } @@ -212,7 +212,7 @@ public: } private: - trantor::Date expiresDate_{ (std::numeric_limits::max)() }; + Date expiresDate_{ (std::numeric_limits::max)() }; bool httpOnly_{ true }; bool secure_{ false }; std::string domain_; diff --git a/web_backends/drogon/drogon/lib/inc/http/HttpRequest.h b/web_backends/drogon/drogon/lib/inc/http/HttpRequest.h index 3ef812f..6538da4 100644 --- a/web_backends/drogon/drogon/lib/inc/http/HttpRequest.h +++ b/web_backends/drogon/drogon/lib/inc/http/HttpRequest.h @@ -248,20 +248,20 @@ public: virtual const std::string &getParameter(const std::string &key) const = 0; /// Return the remote IP address and port - virtual const trantor::InetAddress &peerAddr() const = 0; - const trantor::InetAddress &getPeerAddr() const { + virtual const InetAddress &peerAddr() const = 0; + const InetAddress &getPeerAddr() const { return peerAddr(); } /// Return the local IP address and port - virtual const trantor::InetAddress &localAddr() const = 0; - const trantor::InetAddress &getLocalAddr() const { + virtual const InetAddress &localAddr() const = 0; + const InetAddress &getLocalAddr() const { return localAddr(); } /// Return the creation timestamp set by the framework. - virtual const trantor::Date &creationDate() const = 0; - const trantor::Date &getCreationDate() const { + virtual const Date &creationDate() const = 0; + const Date &getCreationDate() const { return creationDate(); } diff --git a/web_backends/drogon/drogon/lib/inc/http/HttpRequestImpl.cc b/web_backends/drogon/drogon/lib/inc/http/HttpRequestImpl.cc index 43c9076..fcadf45 100644 --- a/web_backends/drogon/drogon/lib/inc/http/HttpRequestImpl.cc +++ b/web_backends/drogon/drogon/lib/inc/http/HttpRequestImpl.cc @@ -143,7 +143,7 @@ void HttpRequestImpl::parseParameters() const { } } -void HttpRequestImpl::appendToBuffer(trantor::MsgBuffer *output) const { +void HttpRequestImpl::appendToBuffer(MsgBuffer *output) const { switch (method_) { case Get: output->append("GET "); diff --git a/web_backends/drogon/drogon/lib/inc/http/HttpRequestImpl.h b/web_backends/drogon/drogon/lib/inc/http/HttpRequestImpl.h index f96e53e..e13075a 100644 --- a/web_backends/drogon/drogon/lib/inc/http/HttpRequestImpl.h +++ b/web_backends/drogon/drogon/lib/inc/http/HttpRequestImpl.h @@ -35,8 +35,8 @@ class HttpRequestImpl : public HttpRequest { public: friend class HttpRequestParser; - explicit HttpRequestImpl(trantor::EventLoop *loop) : - creationDate_(trantor::Date::now()), loop_(loop) { + explicit HttpRequestImpl(EventLoop *loop) : + creationDate_(Date::now()), loop_(loop) { } void reset() { method_ = Invalid; @@ -62,7 +62,7 @@ public: keepAlive_ = true; jsonParsingErrorPtr_.reset(); } - trantor::EventLoop *getLoop() { + EventLoop *getLoop() { return loop_; } @@ -174,27 +174,27 @@ public: return query_; } - virtual const trantor::InetAddress &peerAddr() const override { + virtual const InetAddress &peerAddr() const override { return peer_; } - virtual const trantor::InetAddress &localAddr() const override { + virtual const InetAddress &localAddr() const override { return local_; } - virtual const trantor::Date &creationDate() const override { + virtual const Date &creationDate() const override { return creationDate_; } - void setCreationDate(const trantor::Date &date) { + void setCreationDate(const Date &date) { creationDate_ = date; } - void setPeerAddr(const trantor::InetAddress &peer) { + void setPeerAddr(const InetAddress &peer) { peer_ = peer; } - void setLocalAddr(const trantor::InetAddress &local) { + void setLocalAddr(const InetAddress &local) { local_ = local; } @@ -287,7 +287,7 @@ public: return passThrough_; } - void appendToBuffer(trantor::MsgBuffer *output) const; + void appendToBuffer(MsgBuffer *output) const; virtual const SessionPtr &session() const override { return sessionPtr_; @@ -419,9 +419,9 @@ private: mutable std::shared_ptr jsonPtr_; SessionPtr sessionPtr_; mutable AttributesPtr attributesPtr_; - trantor::InetAddress peer_; - trantor::InetAddress local_; - trantor::Date creationDate_; + InetAddress peer_; + InetAddress local_; + Date creationDate_; std::unique_ptr cacheFilePtr_; mutable std::unique_ptr jsonParsingErrorPtr_; std::unique_ptr expectPtr_; @@ -431,7 +431,7 @@ private: protected: std::string content_; - trantor::EventLoop *loop_; + EventLoop *loop_; mutable ContentType contentType_{ CT_TEXT_PLAIN }; mutable bool flagForParsingContentType_{ false }; std::string contentTypeString_; diff --git a/web_backends/drogon/drogon/lib/inc/http/HttpRequestParser.cc b/web_backends/drogon/drogon/lib/inc/http/HttpRequestParser.cc index bf533ee..5b91f3a 100644 --- a/web_backends/drogon/drogon/lib/inc/http/HttpRequestParser.cc +++ b/web_backends/drogon/drogon/lib/inc/http/HttpRequestParser.cc @@ -22,10 +22,10 @@ #include "core/containers/msg_buffer.h" #include -using namespace trantor; + using namespace drogon; -HttpRequestParser::HttpRequestParser(const trantor::TcpConnectionPtr &connPtr) : +HttpRequestParser::HttpRequestParser(const TcpConnectionPtr &connPtr) : status_(HttpRequestParseStatus::kExpectMethod), loop_(connPtr->getLoop()), conn_(connPtr) { @@ -99,7 +99,7 @@ void HttpRequestParser::reset() { auto req = std::move(requestsPool_.back()); requestsPool_.pop_back(); request_ = std::move(req); - request_->setCreationDate(trantor::Date::now()); + request_->setCreationDate(Date::now()); } } // Return false if any error diff --git a/web_backends/drogon/drogon/lib/inc/http/HttpRequestParser.h b/web_backends/drogon/drogon/lib/inc/http/HttpRequestParser.h index becee1e..3568d71 100644 --- a/web_backends/drogon/drogon/lib/inc/http/HttpRequestParser.h +++ b/web_backends/drogon/drogon/lib/inc/http/HttpRequestParser.h @@ -23,7 +23,7 @@ #include namespace drogon { -class HttpRequestParser : public trantor::NonCopyable, +class HttpRequestParser : public NonCopyable, public std::enable_shared_from_this { public: enum class HttpRequestParseStatus { @@ -37,10 +37,10 @@ public: kGotAll, }; - explicit HttpRequestParser(const trantor::TcpConnectionPtr &connPtr); + explicit HttpRequestParser(const TcpConnectionPtr &connPtr); // return false if any error - bool parseRequest(trantor::MsgBuffer *buf); + bool parseRequest(MsgBuffer *buf); bool gotAll() const { return status_ == HttpRequestParseStatus::kGotAll; @@ -88,7 +88,7 @@ public: size_t numberOfRequestsParsed() const { return requestsCounter_; } - trantor::MsgBuffer &getBuffer() { + MsgBuffer &getBuffer() { return sendBuffer_; } std::vector > &getResponseBuffer() { @@ -114,16 +114,16 @@ private: void shutdownConnection(HttpStatusCode code); bool processRequestLine(const char *begin, const char *end); HttpRequestParseStatus status_; - trantor::EventLoop *loop_; + EventLoop *loop_; HttpRequestImplPtr request_; bool firstRequest_{ true }; WebSocketConnectionImplPtr websockConnPtr_; std::deque > > requestPipelining_; size_t requestsCounter_{ 0 }; - std::weak_ptr conn_; + std::weak_ptr conn_; bool stopWorking_{ false }; - trantor::MsgBuffer sendBuffer_; + MsgBuffer sendBuffer_; std::unique_ptr > > responseBuffer_; std::unique_ptr > requestBuffer_; diff --git a/web_backends/drogon/drogon/lib/inc/http/HttpResponse.h b/web_backends/drogon/drogon/lib/inc/http/HttpResponse.h index c8bc146..112fb41 100644 --- a/web_backends/drogon/drogon/lib/inc/http/HttpResponse.h +++ b/web_backends/drogon/drogon/lib/inc/http/HttpResponse.h @@ -101,8 +101,8 @@ public: } /// Get the creation timestamp of the response. - virtual const trantor::Date &creationDate() const = 0; - const trantor::Date &getCreationDate() const { + virtual const Date &creationDate() const = 0; + const Date &getCreationDate() const { return creationDate(); } diff --git a/web_backends/drogon/drogon/lib/inc/http/HttpResponseImpl.cc b/web_backends/drogon/drogon/lib/inc/http/HttpResponseImpl.cc index 1bcd55f..c1102e5 100644 --- a/web_backends/drogon/drogon/lib/inc/http/HttpResponseImpl.cc +++ b/web_backends/drogon/drogon/lib/inc/http/HttpResponseImpl.cc @@ -25,7 +25,7 @@ #ifdef _WIN32 #define stat _stati64 #endif -using namespace trantor; + using namespace drogon; namespace drogon { @@ -98,7 +98,7 @@ void HttpResponseImpl::generateBodyFromJson() const { } HttpResponsePtr HttpResponse::newNotFoundResponse() { - auto loop = trantor::EventLoop::getEventLoopOfCurrentThread(); + auto loop = EventLoop::getEventLoopOfCurrentThread(); auto &resp = HttpAppFrameworkImpl::instance().getCustom404Page(); if (resp) { if (loop && loop->index() < app().getThreadNum()) { @@ -243,7 +243,7 @@ HttpResponsePtr HttpResponse::newFileResponse(const std::string &fullPath, const return resp; } -void HttpResponseImpl::makeHeaderString(trantor::MsgBuffer &buffer) { +void HttpResponseImpl::makeHeaderString(MsgBuffer &buffer) { buffer.ensureWritableBytes(128); int len{ 0 }; if (version_ == Version::kHttp11) { @@ -320,7 +320,7 @@ void HttpResponseImpl::makeHeaderString(trantor::MsgBuffer &buffer) { buffer.append("\r\n"); } } -void HttpResponseImpl::renderToBuffer(trantor::MsgBuffer &buffer) { +void HttpResponseImpl::renderToBuffer(MsgBuffer &buffer) { if (expriedTime_ >= 0) { auto strPtr = renderToBuffer(); buffer.append(strPtr->peek(), strPtr->readableBytes()); @@ -344,7 +344,7 @@ void HttpResponseImpl::renderToBuffer(trantor::MsgBuffer &buffer) { if (!passThrough_ && drogon::HttpAppFrameworkImpl::instance().sendDateHeader()) { buffer.append("date: "); - buffer.append(utils::getHttpFullDate(trantor::Date::date()), + buffer.append(utils::getHttpFullDate(Date::date()), httpFullDateStringLength); buffer.append("\r\n\r\n"); } else { @@ -353,12 +353,12 @@ void HttpResponseImpl::renderToBuffer(trantor::MsgBuffer &buffer) { if (bodyPtr_) buffer.append(bodyPtr_->data(), bodyPtr_->length()); } -std::shared_ptr HttpResponseImpl::renderToBuffer() { +std::shared_ptr HttpResponseImpl::renderToBuffer() { if (expriedTime_ >= 0) { if (!passThrough_ && drogon::HttpAppFrameworkImpl::instance().sendDateHeader()) { if (datePos_ != static_cast(-1)) { - auto now = trantor::Date::now(); + auto now = Date::now(); bool isDateChanged = ((now.microSecondsSinceEpoch() / MICRO_SECONDS_PRE_SEC) != httpStringDate_); @@ -369,7 +369,7 @@ std::shared_ptr HttpResponseImpl::renderToBuffer() { auto newDate = utils::getHttpFullDate(now); httpString_ = - std::make_shared(*httpString_); + std::make_shared(*httpString_); memcpy((void *)&(*httpString_)[datePos_], newDate, httpFullDateStringLength); @@ -383,7 +383,7 @@ std::shared_ptr HttpResponseImpl::renderToBuffer() { return httpString_; } } - auto httpString = std::make_shared(256); + auto httpString = std::make_shared(256); if (!fullHeaderString_) { makeHeaderString(*httpString); } else { @@ -402,7 +402,7 @@ std::shared_ptr HttpResponseImpl::renderToBuffer() { drogon::HttpAppFrameworkImpl::instance().sendDateHeader()) { httpString->append("date: "); auto datePos = httpString->readableBytes(); - httpString->append(utils::getHttpFullDate(trantor::Date::date()), + httpString->append(utils::getHttpFullDate(Date::date()), httpFullDateStringLength); httpString->append("\r\n\r\n"); datePos_ = datePos; @@ -420,9 +420,9 @@ std::shared_ptr HttpResponseImpl::renderToBuffer() { return httpString; } -std::shared_ptr HttpResponseImpl:: +std::shared_ptr HttpResponseImpl:: renderHeaderForHeadMethod() { - auto httpString = std::make_shared(256); + auto httpString = std::make_shared(256); if (!fullHeaderString_) { makeHeaderString(*httpString); } else { @@ -440,7 +440,7 @@ std::shared_ptr HttpResponseImpl:: if (!passThrough_ && drogon::HttpAppFrameworkImpl::instance().sendDateHeader()) { httpString->append("date: "); - httpString->append(utils::getHttpFullDate(trantor::Date::date()), + httpString->append(utils::getHttpFullDate(Date::date()), httpFullDateStringLength); httpString->append("\r\n\r\n"); } else { diff --git a/web_backends/drogon/drogon/lib/inc/http/HttpResponseImpl.h b/web_backends/drogon/drogon/lib/inc/http/HttpResponseImpl.h index 22fd499..79fbc32 100644 --- a/web_backends/drogon/drogon/lib/inc/http/HttpResponseImpl.h +++ b/web_backends/drogon/drogon/lib/inc/http/HttpResponseImpl.h @@ -34,12 +34,12 @@ class HttpResponseImpl : public HttpResponse { public: HttpResponseImpl() : - creationDate_(trantor::Date::now()) { + creationDate_(Date::now()) { } HttpResponseImpl(HttpStatusCode code, ContentType type) : statusCode_(code), statusMessage_(statusCodeToString(code)), - creationDate_(trantor::Date::now()), + creationDate_(Date::now()), contentType_(type), flagForParsingContentType_(true), contentTypeString_(webContentTypeToString(type)) { @@ -51,7 +51,7 @@ public: return statusCode_; } - const trantor::Date &creationDate() const override { + const Date &creationDate() const override { return creationDate_; } @@ -199,9 +199,9 @@ public: void redirect(const std::string &url) { headers_["location"] = url; } - std::shared_ptr renderToBuffer(); - void renderToBuffer(trantor::MsgBuffer &buffer); - std::shared_ptr renderHeaderForHeadMethod(); + std::shared_ptr renderToBuffer(); + void renderToBuffer(MsgBuffer &buffer); + std::shared_ptr renderHeaderForHeadMethod(); void clear() override; void setExpiredTime(ssize_t expiredTime) override { @@ -266,7 +266,7 @@ public: sendfileName_ = filename; } void makeHeaderString() { - fullHeaderString_ = std::make_shared(128); + fullHeaderString_ = std::make_shared(128); makeHeaderString(*fullHeaderString_); } @@ -295,7 +295,7 @@ public: ~HttpResponseImpl() override = default; protected: - void makeHeaderString(trantor::MsgBuffer &headerString); + void makeHeaderString(MsgBuffer &headerString); private: void setBody(const char *body, size_t len) override { @@ -327,7 +327,7 @@ private: HttpStatusCode statusCode_{ kUnknown }; string_view statusMessage_; - trantor::Date creationDate_; + Date creationDate_; Version version_{ Version::kHttp11 }; bool closeConnection_{ false }; mutable std::shared_ptr bodyPtr_; @@ -335,8 +335,8 @@ private: std::string sendfileName_; mutable std::shared_ptr jsonPtr_; - std::shared_ptr fullHeaderString_; - mutable std::shared_ptr httpString_; + std::shared_ptr fullHeaderString_; + mutable std::shared_ptr httpString_; mutable size_t datePos_{ static_cast(-1) }; mutable int64_t httpStringDate_{ -1 }; mutable bool flagForParsingJson_{ false }; diff --git a/web_backends/drogon/drogon/lib/inc/http/HttpResponseParser.cc b/web_backends/drogon/drogon/lib/inc/http/HttpResponseParser.cc index 62d0637..568202f 100644 --- a/web_backends/drogon/drogon/lib/inc/http/HttpResponseParser.cc +++ b/web_backends/drogon/drogon/lib/inc/http/HttpResponseParser.cc @@ -17,7 +17,7 @@ #include "core/log/logger.h" #include "core/containers/msg_buffer.h" #include -using namespace trantor; + using namespace drogon; void HttpResponseParser::reset() { @@ -28,7 +28,7 @@ void HttpResponseParser::reset() { currentChunkLength_ = 0; } -HttpResponseParser::HttpResponseParser(const trantor::TcpConnectionPtr &connPtr) : +HttpResponseParser::HttpResponseParser(const TcpConnectionPtr &connPtr) : status_(HttpResponseParseStatus::kExpectResponseLine), responsePtr_(new HttpResponseImpl), conn_(connPtr) { diff --git a/web_backends/drogon/drogon/lib/inc/http/HttpResponseParser.h b/web_backends/drogon/drogon/lib/inc/http/HttpResponseParser.h index 3cfd99a..27c35dd 100644 --- a/web_backends/drogon/drogon/lib/inc/http/HttpResponseParser.h +++ b/web_backends/drogon/drogon/lib/inc/http/HttpResponseParser.h @@ -22,7 +22,7 @@ #include namespace drogon { -class HttpResponseParser : public trantor::NonCopyable { +class HttpResponseParser : public NonCopyable { public: enum class HttpResponseParseStatus { kExpectResponseLine, @@ -35,12 +35,12 @@ public: kGotAll, }; - explicit HttpResponseParser(const trantor::TcpConnectionPtr &connPtr); + explicit HttpResponseParser(const TcpConnectionPtr &connPtr); // default copy-ctor, dtor and assignment are fine // return false if any error - bool parseResponse(trantor::MsgBuffer *buf); + bool parseResponse(MsgBuffer *buf); bool parseResponseOnClose(); bool gotAll() const { @@ -65,7 +65,7 @@ private: bool parseResponseForHeadMethod_{ false }; size_t leftBodyLength_{ 0 }; size_t currentChunkLength_{ 0 }; - std::weak_ptr conn_; + std::weak_ptr conn_; }; } // namespace drogon diff --git a/web_backends/drogon/drogon/lib/inc/http/SessionManager.cc b/web_backends/drogon/drogon/lib/inc/http/SessionManager.cc index 690bd12..233b65b 100644 --- a/web_backends/drogon/drogon/lib/inc/http/SessionManager.cc +++ b/web_backends/drogon/drogon/lib/inc/http/SessionManager.cc @@ -17,7 +17,7 @@ using namespace drogon; -SessionManager::SessionManager(trantor::EventLoop *loop, size_t timeout) : +SessionManager::SessionManager(EventLoop *loop, size_t timeout) : loop_(loop), timeout_(timeout) { if (timeout_ > 0) { size_t wheelNum = 1; diff --git a/web_backends/drogon/drogon/lib/inc/http/SessionManager.h b/web_backends/drogon/drogon/lib/inc/http/SessionManager.h index 02ca147..139a6a8 100644 --- a/web_backends/drogon/drogon/lib/inc/http/SessionManager.h +++ b/web_backends/drogon/drogon/lib/inc/http/SessionManager.h @@ -23,9 +23,9 @@ #include namespace drogon { -class SessionManager : public trantor::NonCopyable { +class SessionManager : public NonCopyable { public: - SessionManager(trantor::EventLoop *loop, size_t timeout); + SessionManager(EventLoop *loop, size_t timeout); ~SessionManager() { sessionMapPtr_.reset(); } @@ -34,7 +34,7 @@ public: private: std::unique_ptr > sessionMapPtr_; - trantor::EventLoop *loop_; + EventLoop *loop_; size_t timeout_; }; } // namespace drogon diff --git a/web_backends/drogon/drogon/lib/src/AccessLogger.cc b/web_backends/drogon/drogon/lib/src/AccessLogger.cc index 855fbfa..d7275d4 100644 --- a/web_backends/drogon/drogon/lib/src/AccessLogger.cc +++ b/web_backends/drogon/drogon/lib/src/AccessLogger.cc @@ -35,13 +35,13 @@ void AccessLogger::initAndStart(const Json::Value &config) { logFunctionMap_ = { { "$request_path", outputReqPath }, { "$path", outputReqPath }, { "$date", - [this](trantor::LogStream &stream, + [this](LogStream &stream, const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &resp) { outputDate(stream, req, resp); } }, { "$request_date", - [this](trantor::LogStream &stream, + [this](LogStream &stream, const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &resp) { outputReqDate(stream, req, resp); @@ -85,7 +85,7 @@ void AccessLogger::initAndStart(const Json::Value &config) { asyncFileLogger_.setFileName(fileName, extension, logPath); asyncFileLogger_.startLogging(); logIndex_ = config.get("log_index", 0).asInt(); - trantor::Logger::setOutputFunction( + Logger::setOutputFunction( [&](const char *msg, const uint64_t len) { asyncFileLogger_.output(msg, len); }, @@ -106,7 +106,7 @@ void AccessLogger::initAndStart(const Json::Value &config) { void AccessLogger::shutdown() { } -void AccessLogger::logging(trantor::LogStream &stream, +void AccessLogger::logging(LogStream &stream, const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &resp) { for (auto &func : logFunctions_) { @@ -128,7 +128,7 @@ void AccessLogger::createLogFunctions(std::string format) { if (std::regex_search(format, m, e)) { if (!rawString.empty()) { logFunctions_.emplace_back( - [rawString](trantor::LogStream &stream, + [rawString](LogStream &stream, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &) { stream << rawString; @@ -150,14 +150,14 @@ void AccessLogger::createLogFunctions(std::string format) { if (!rawString.empty()) { logFunctions_.emplace_back( [rawString = - std::move(rawString)](trantor::LogStream &stream, + std::move(rawString)](LogStream &stream, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &) { stream << rawString << "\n"; }); } else { logFunctions_.emplace_back( - [](trantor::LogStream &stream, + [](LogStream &stream, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &) { stream << "\n"; }); } @@ -172,7 +172,7 @@ AccessLogger::LogFunction AccessLogger::newLogFunction( if (placeholder.find("$http_") == 0 && placeholder.size() > 6) { auto headerName = placeholder.substr(6); return [headerName = - std::move(headerName)](trantor::LogStream &stream, + std::move(headerName)](LogStream &stream, const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &) { outputReqHeader(stream, req, headerName); @@ -181,7 +181,7 @@ AccessLogger::LogFunction AccessLogger::newLogFunction( if (placeholder.find("$cookie_") == 0 && placeholder.size() > 8) { auto cookieName = placeholder.substr(8); return [cookieName = - std::move(cookieName)](trantor::LogStream &stream, + std::move(cookieName)](LogStream &stream, const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &) { outputReqCookie(stream, req, cookieName); @@ -190,36 +190,36 @@ AccessLogger::LogFunction AccessLogger::newLogFunction( if (placeholder.find("$upstream_http_") == 0 && placeholder.size() > 15) { auto headerName = placeholder.substr(15); return [headerName = std::move( - headerName)](trantor::LogStream &stream, + headerName)](LogStream &stream, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &resp) { outputRespHeader(stream, resp, headerName); }; } - return [placeholder](trantor::LogStream &stream, + return [placeholder](LogStream &stream, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &) { stream << placeholder; }; } -void AccessLogger::outputReqPath(trantor::LogStream &stream, +void AccessLogger::outputReqPath(LogStream &stream, const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &) { stream << req->path(); } -void AccessLogger::outputDate(trantor::LogStream &stream, +void AccessLogger::outputDate(LogStream &stream, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &) const { if (useLocalTime_) { - stream << trantor::Date::now().toFormattedStringLocal(true); + stream << Date::now().toFormattedStringLocal(true); } else { - stream << trantor::Date::now().toFormattedString(true); + stream << Date::now().toFormattedString(true); } } -void AccessLogger::outputReqDate(trantor::LogStream &stream, +void AccessLogger::outputReqDate(LogStream &stream, const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &) const { if (useLocalTime_) { @@ -230,13 +230,13 @@ void AccessLogger::outputReqDate(trantor::LogStream &stream, } //$request_query -void AccessLogger::outputReqQuery(trantor::LogStream &stream, +void AccessLogger::outputReqQuery(LogStream &stream, const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &) { stream << req->query(); } //$request_url -void AccessLogger::outputReqURL(trantor::LogStream &stream, +void AccessLogger::outputReqURL(LogStream &stream, const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &) { auto &query = req->query(); @@ -247,36 +247,36 @@ void AccessLogger::outputReqURL(trantor::LogStream &stream, } } -void AccessLogger::outputRemoteAddr(trantor::LogStream &stream, +void AccessLogger::outputRemoteAddr(LogStream &stream, const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &) { stream << req->peerAddr().toIpPort(); } -void AccessLogger::outputLocalAddr(trantor::LogStream &stream, +void AccessLogger::outputLocalAddr(LogStream &stream, const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &) { stream << req->localAddr().toIpPort(); } -void AccessLogger::outputReqLength(trantor::LogStream &stream, +void AccessLogger::outputReqLength(LogStream &stream, const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &) { stream << req->body().length(); } -void AccessLogger::outputRespLength(trantor::LogStream &stream, +void AccessLogger::outputRespLength(LogStream &stream, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &resp) { stream << resp->body().length(); } -void AccessLogger::outputMethod(trantor::LogStream &stream, +void AccessLogger::outputMethod(LogStream &stream, const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &) { stream << req->methodString(); } -void AccessLogger::outputThreadNumber(trantor::LogStream &stream, +void AccessLogger::outputThreadNumber(LogStream &stream, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &) { #ifdef __linux__ @@ -310,45 +310,45 @@ void AccessLogger::outputThreadNumber(trantor::LogStream &stream, } //$http_[header_name] -void AccessLogger::outputReqHeader(trantor::LogStream &stream, +void AccessLogger::outputReqHeader(LogStream &stream, const drogon::HttpRequestPtr &req, const std::string &headerName) { stream << headerName << ": " << req->getHeader(headerName); } //$cookie_[cookie_name] -void AccessLogger::outputReqCookie(trantor::LogStream &stream, +void AccessLogger::outputReqCookie(LogStream &stream, const drogon::HttpRequestPtr &req, const std::string &cookie) { stream << "(cookie)" << cookie << "=" << req->getCookie(cookie); } //$upstream_http_[header_name] -void AccessLogger::outputRespHeader(trantor::LogStream &stream, +void AccessLogger::outputRespHeader(LogStream &stream, const drogon::HttpResponsePtr &resp, const std::string &headerName) { stream << headerName << ": " << resp->getHeader(headerName); } //$status -void AccessLogger::outputStatusString(trantor::LogStream &stream, +void AccessLogger::outputStatusString(LogStream &stream, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &resp) { int code = resp->getStatusCode(); stream << code << " " << statusCodeToString(code); } //$status_code -void AccessLogger::outputStatusCode(trantor::LogStream &stream, +void AccessLogger::outputStatusCode(LogStream &stream, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &resp) { stream << resp->getStatusCode(); } //$processing_time -void AccessLogger::outputProcessingTime(trantor::LogStream &stream, +void AccessLogger::outputProcessingTime(LogStream &stream, const drogon::HttpRequestPtr &req, const drogon::HttpResponsePtr &) { auto start = req->creationDate(); - auto end = trantor::Date::now(); + auto end = Date::now(); auto duration = end.microSecondsSinceEpoch() - start.microSecondsSinceEpoch(); auto seconds = static_cast(duration) / 1000000.0; @@ -356,7 +356,7 @@ void AccessLogger::outputProcessingTime(trantor::LogStream &stream, } //$upstream_http_content-type $upstream_http_content_type -void AccessLogger::outputRespContentType(trantor::LogStream &stream, +void AccessLogger::outputRespContentType(LogStream &stream, const drogon::HttpRequestPtr &, const drogon::HttpResponsePtr &resp) { auto typeStr = webContentTypeToString(resp->contentType()); diff --git a/web_backends/drogon/drogon/lib/src/HttpAppFrameworkImpl.cc b/web_backends/drogon/drogon/lib/src/HttpAppFrameworkImpl.cc index 18023dd..d86b9d4 100644 --- a/web_backends/drogon/drogon/lib/src/HttpAppFrameworkImpl.cc +++ b/web_backends/drogon/drogon/lib/src/HttpAppFrameworkImpl.cc @@ -365,8 +365,8 @@ HttpAppFramework &HttpAppFrameworkImpl::setLogPath( return *this; } HttpAppFramework &HttpAppFrameworkImpl::setLogLevel( - trantor::Logger::LogLevel level) { - trantor::Logger::setLogLevel(level); + Logger::LogLevel level) { + Logger::setLogLevel(level); return *this; } HttpAppFramework &HttpAppFrameworkImpl::setSSLConfigCommands( @@ -386,7 +386,7 @@ void HttpAppFrameworkImpl::run() { getLoop()->moveToCurrentThread(); } LOG_TRACE << "Start to run..."; - trantor::AsyncFileLogger asyncFileLogger; + AsyncFileLogger asyncFileLogger; // Create dirs for cache files for (int i = 0; i < 256; ++i) { char dirName[4]; @@ -443,7 +443,7 @@ void HttpAppFrameworkImpl::run() { asyncFileLogger.setFileName(baseName, ".log", logPath_); asyncFileLogger.startLogging(); - trantor::Logger::setOutputFunction( + Logger::setOutputFunction( [&](const char *msg, const uint64_t len) { asyncFileLogger.output(msg, len); }, @@ -518,7 +518,7 @@ void HttpAppFrameworkImpl::run() { getLoop()->loop(); } -void HttpAppFrameworkImpl::onConnection(const trantor::TcpConnectionPtr &conn) { +void HttpAppFrameworkImpl::onConnection(const TcpConnectionPtr &conn) { static std::mutex mtx; LOG_TRACE << "connect!!!" << maxConnectionNum_ << " num=" << connectionNum_.load(); @@ -737,13 +737,13 @@ void HttpAppFrameworkImpl::onAsyncRequest( }*/ } -trantor::EventLoop *HttpAppFrameworkImpl::getLoop() const { - //static trantor::EventLoop loop; +EventLoop *HttpAppFrameworkImpl::getLoop() const { + //static EventLoop loop; //return &loop;] return nullptr; } -trantor::EventLoop *HttpAppFrameworkImpl::getIOLoop(size_t id) const { +EventLoop *HttpAppFrameworkImpl::getIOLoop(size_t id) const { assert(listenerManagerPtr_); return listenerManagerPtr_->getIOLoop(id); } @@ -781,7 +781,7 @@ void HttpAppFrameworkImpl::forward( clientPtr = iter->second; } else { clientPtr = std::make_shared( - trantor::EventLoop::getEventLoopOfCurrentThread() ? trantor::EventLoop::getEventLoopOfCurrentThread() : getLoop(), + EventLoop::getEventLoopOfCurrentThread() ? EventLoop::getEventLoopOfCurrentThread() : getLoop(), hostString); clientsMap[hostString] = clientPtr; } @@ -815,7 +815,7 @@ const HttpResponsePtr &HttpAppFrameworkImpl::getCustom404Page() { if (!custom404_) { return custom404_; } - auto loop = trantor::EventLoop::getEventLoopOfCurrentThread(); + auto loop = EventLoop::getEventLoopOfCurrentThread(); if (loop && loop->index() < app().getThreadNum()) { // If the current thread is an IO thread static IOThreadStorage thread404Pages; @@ -869,7 +869,7 @@ const std::function return customErrorHandler_; } -std::vector HttpAppFrameworkImpl::getListeners() const { +std::vector HttpAppFrameworkImpl::getListeners() const { return listenerManagerPtr_->getListeners(); } HttpAppFramework &HttpAppFrameworkImpl::setDefaultHandler( diff --git a/web_backends/drogon/drogon/lib/src/HttpAppFrameworkImpl.h b/web_backends/drogon/drogon/lib/src/HttpAppFrameworkImpl.h index 1fce1ad..b53189e 100644 --- a/web_backends/drogon/drogon/lib/src/HttpAppFrameworkImpl.h +++ b/web_backends/drogon/drogon/lib/src/HttpAppFrameworkImpl.h @@ -114,8 +114,8 @@ public: } HttpAppFramework ®isterNewConnectionAdvice( - const std::function &advice) + const std::function &advice) override { newConnectionAdvices_.emplace_back(advice); return *this; @@ -222,8 +222,8 @@ public: const std::string &getUploadPath() const override { return uploadPath_; } - const std::shared_ptr &getResolver() const override { - static auto resolver = trantor::Resolver::newResolver(getLoop()); + const std::shared_ptr &getResolver() const override { + static auto resolver = Resolver::newResolver(getLoop()); return resolver; } HttpAppFramework &setUploadPath(const std::string &uploadPath) override; @@ -255,7 +255,7 @@ public: HttpAppFramework &setLogPath(const std::string &logPath, const std::string &logfileBaseName, size_t logfileSize) override; - HttpAppFramework &setLogLevel(trantor::Logger::LogLevel level) override; + HttpAppFramework &setLogLevel(Logger::LogLevel level) override; HttpAppFramework &enableSendfile(bool sendFile) override { useSendfile_ = sendFile; return *this; @@ -365,9 +365,9 @@ public: const noexcept override { return floatPrecisionInJson_; } - trantor::EventLoop *getLoop() const override; + EventLoop *getLoop() const override; - trantor::EventLoop *getIOLoop(size_t id) const override; + EventLoop *getIOLoop(size_t id) const override; void quit() override; @@ -396,7 +396,7 @@ public: return serverHeader_; } - std::vector getListeners() const override; + std::vector getListeners() const override; inline static HttpAppFrameworkImpl &instance() { static HttpAppFrameworkImpl instance; return instance; @@ -417,7 +417,7 @@ public: } size_t getCurrentThreadIndex() const override { - auto *loop = trantor::EventLoop::getEventLoopOfCurrentThread(); + auto *loop = EventLoop::getEventLoopOfCurrentThread(); if (loop) { return loop->index(); } @@ -466,7 +466,7 @@ private: const HttpRequestImplPtr &req, std::function &&callback, const WebSocketConnectionImplPtr &wsConnPtr); - void onConnection(const trantor::TcpConnectionPtr &conn); + void onConnection(const TcpConnectionPtr &conn); void findSessionForRequest(const HttpRequestImplPtr &req); @@ -539,8 +539,8 @@ private: bool enableDateHeader_{ true }; bool reusePort_{ false }; std::vector > beginningAdvices_; - std::vector > + std::vector > newConnectionAdvices_; std::vector > responseCreationAdvices_; diff --git a/web_backends/drogon/drogon/lib/src/HttpClientImpl.cc b/web_backends/drogon/drogon/lib/src/HttpClientImpl.cc index 14fb675..ce90f9d 100644 --- a/web_backends/drogon/drogon/lib/src/HttpClientImpl.cc +++ b/web_backends/drogon/drogon/lib/src/HttpClientImpl.cc @@ -21,16 +21,16 @@ #include #include -using namespace trantor; + using namespace drogon; using namespace std::placeholders; -namespace trantor { + const static size_t kDefaultDNSTimeout{ 600 }; -} + void HttpClientImpl::createTcpClient() { LOG_TRACE << "New TcpClient," << serverAddr_.toIpPort(); tcpClientPtr_ = - std::make_shared(loop_, serverAddr_, "httpClient"); + std::make_shared(loop_, serverAddr_, "httpClient"); #ifdef OPENSSL_FOUND if (useSSL_) { @@ -43,7 +43,7 @@ void HttpClientImpl::createTcpClient() { std::weak_ptr weakPtr = thisPtr; tcpClientPtr_->setConnectionCallback( - [weakPtr](const trantor::TcpConnectionPtr &connPtr) { + [weakPtr](const TcpConnectionPtr &connPtr) { auto thisPtr = weakPtr.lock(); if (!thisPtr) return; @@ -89,8 +89,8 @@ void HttpClientImpl::createTcpClient() { thisPtr->onError(ReqResult::BadServerAddress); }); tcpClientPtr_->setMessageCallback( - [weakPtr](const trantor::TcpConnectionPtr &connPtr, - trantor::MsgBuffer *msg) { + [weakPtr](const TcpConnectionPtr &connPtr, + MsgBuffer *msg) { auto thisPtr = weakPtr.lock(); if (thisPtr) { thisPtr->onRecvMessage(connPtr, msg); @@ -100,9 +100,9 @@ void HttpClientImpl::createTcpClient() { auto thisPtr = weakPtr.lock(); if (!thisPtr) return; - if (err == trantor::SSLError::kSSLHandshakeError) + if (err == SSLError::kSSLHandshakeError) thisPtr->onError(ReqResult::HandshakeError); - else if (err == trantor::SSLError::kSSLInvalidCertificate) + else if (err == SSLError::kSSLInvalidCertificate) thisPtr->onError(ReqResult::InvalidCertificate); else { LOG_FATAL << "Invalid value for SSLError"; @@ -112,8 +112,8 @@ void HttpClientImpl::createTcpClient() { tcpClientPtr_->connect(); } -HttpClientImpl::HttpClientImpl(trantor::EventLoop *loop, - const trantor::InetAddress &addr, +HttpClientImpl::HttpClientImpl(EventLoop *loop, + const InetAddress &addr, bool useSSL, bool useOldTLS, bool validateCert) : @@ -124,7 +124,7 @@ HttpClientImpl::HttpClientImpl(trantor::EventLoop *loop, useOldTLS_(useOldTLS) { } -HttpClientImpl::HttpClientImpl(trantor::EventLoop *loop, +HttpClientImpl::HttpClientImpl(EventLoop *loop, const std::string &hostString, bool useOldTLS, bool validateCert) : @@ -285,7 +285,7 @@ void HttpClientImpl::sendRequestInLoop(const drogon::HttpRequestPtr &req, } for (auto &cookie : validCookies_) { if ((cookie.expiresDate().microSecondsSinceEpoch() == 0 || - cookie.expiresDate() > trantor::Date::now()) && + cookie.expiresDate() > Date::now()) && (cookie.path().empty() || req->path().find(cookie.path()) == 0)) { req->addCookie(cookie.key(), cookie.value()); } @@ -316,13 +316,13 @@ void HttpClientImpl::sendRequestInLoop(const drogon::HttpRequestPtr &req, dns_ = true; if (!resolverPtr_) { resolverPtr_ = - trantor::Resolver::newResolver(loop_, + Resolver::newResolver(loop_, kDefaultDNSTimeout); } resolverPtr_->resolve( domain_, [thisPtr = shared_from_this(), - hasIpv6Address](const trantor::InetAddress &addr) { + hasIpv6Address](const InetAddress &addr) { thisPtr->loop_->runInLoop([thisPtr, addr, hasIpv6Address]() { @@ -394,9 +394,9 @@ void HttpClientImpl::sendRequestInLoop(const drogon::HttpRequestPtr &req, } } -void HttpClientImpl::sendReq(const trantor::TcpConnectionPtr &connPtr, +void HttpClientImpl::sendReq(const TcpConnectionPtr &connPtr, const HttpRequestPtr &req) { - trantor::MsgBuffer buffer; + MsgBuffer buffer; assert(req); auto implPtr = static_cast(req.get()); implPtr->appendToBuffer(&buffer); @@ -409,7 +409,7 @@ void HttpClientImpl::sendReq(const trantor::TcpConnectionPtr &connPtr, void HttpClientImpl::handleResponse( const HttpResponseImplPtr &resp, std::pair &&reqAndCb, - const trantor::TcpConnectionPtr &connPtr) { + const TcpConnectionPtr &connPtr) { assert(!pipeliningCallbacks_.empty()); auto &type = resp->getHeaderBy("content-type"); auto &coding = resp->getHeaderBy("content-encoding"); @@ -452,8 +452,8 @@ void HttpClientImpl::handleResponse( } } } -void HttpClientImpl::onRecvMessage(const trantor::TcpConnectionPtr &connPtr, - trantor::MsgBuffer *msg) { +void HttpClientImpl::onRecvMessage(const TcpConnectionPtr &connPtr, + MsgBuffer *msg) { auto responseParser = connPtr->getContext(); // LOG_TRACE << "###:" << msg->readableBytes(); @@ -488,20 +488,20 @@ void HttpClientImpl::onRecvMessage(const trantor::TcpConnectionPtr &connPtr, HttpClientPtr HttpClient::newHttpClient(const std::string &ip, uint16_t port, bool useSSL, - trantor::EventLoop *loop, + EventLoop *loop, bool useOldTLS, bool validateCert) { bool isIpv6 = ip.find(':') == std::string::npos ? false : true; return std::make_shared( loop == nullptr ? HttpAppFrameworkImpl::instance().getLoop() : loop, - trantor::InetAddress(ip, port, isIpv6), + InetAddress(ip, port, isIpv6), useSSL, useOldTLS, validateCert); } HttpClientPtr HttpClient::newHttpClient(const std::string &hostString, - trantor::EventLoop *loop, + EventLoop *loop, bool useOldTLS, bool validateCert) { return std::make_shared( diff --git a/web_backends/drogon/drogon/lib/src/HttpClientImpl.h b/web_backends/drogon/drogon/lib/src/HttpClientImpl.h index 1b6f184..ff5e588 100644 --- a/web_backends/drogon/drogon/lib/src/HttpClientImpl.h +++ b/web_backends/drogon/drogon/lib/src/HttpClientImpl.h @@ -29,12 +29,12 @@ namespace drogon { class HttpClientImpl final : public HttpClient, public std::enable_shared_from_this { public: - HttpClientImpl(trantor::EventLoop *loop, - const trantor::InetAddress &addr, + HttpClientImpl(EventLoop *loop, + const InetAddress &addr, bool useSSL = false, bool useOldTLS = false, bool validateCert = true); - HttpClientImpl(trantor::EventLoop *loop, + HttpClientImpl(EventLoop *loop, const std::string &hostString, bool useOldTLS = false, bool validateCert = true); @@ -44,7 +44,7 @@ public: void sendRequest(const HttpRequestPtr &req, HttpReqCallback &&callback, double timeout = 0) override; - trantor::EventLoop *getLoop() override { + EventLoop *getLoop() override { return loop_; } void setPipeliningDepth(size_t depth) override { @@ -75,12 +75,12 @@ public: } private: - std::shared_ptr tcpClientPtr_; - trantor::EventLoop *loop_; - trantor::InetAddress serverAddr_; + std::shared_ptr tcpClientPtr_; + EventLoop *loop_; + InetAddress serverAddr_; bool useSSL_; bool validateCert_; - void sendReq(const trantor::TcpConnectionPtr &connPtr, + void sendReq(const TcpConnectionPtr &connPtr, const HttpRequestPtr &req); void sendRequestInLoop(const HttpRequestPtr &req, HttpReqCallback &&callback); @@ -90,11 +90,11 @@ private: void handleCookies(const HttpResponseImplPtr &resp); void handleResponse(const HttpResponseImplPtr &resp, std::pair &&reqAndCb, - const trantor::TcpConnectionPtr &connPtr); + const TcpConnectionPtr &connPtr); void createTcpClient(); std::queue > pipeliningCallbacks_; std::list > requestsBuffer_; - void onRecvMessage(const trantor::TcpConnectionPtr &, trantor::MsgBuffer *); + void onRecvMessage(const TcpConnectionPtr &, MsgBuffer *); void onError(ReqResult result); std::string domain_; size_t pipeliningDepth_{ 0 }; @@ -103,7 +103,7 @@ private: size_t bytesSent_{ 0 }; size_t bytesReceived_{ 0 }; bool dns_{ false }; - std::shared_ptr resolverPtr_; + std::shared_ptr resolverPtr_; bool useOldTLS_{ false }; std::string userAgent_{ "DrogonClient" }; }; diff --git a/web_backends/drogon/drogon/lib/src/HttpServer.cc b/web_backends/drogon/drogon/lib/src/HttpServer.cc index 68e38d2..2fa3de3 100644 --- a/web_backends/drogon/drogon/lib/src/HttpServer.cc +++ b/web_backends/drogon/drogon/lib/src/HttpServer.cc @@ -35,7 +35,7 @@ using namespace std::placeholders; using namespace drogon; -using namespace trantor; + namespace drogon { static HttpResponsePtr getCompressedResponse(const HttpRequestImplPtr &req, const HttpResponsePtr &response, @@ -127,7 +127,7 @@ static void defaultWebSockAsyncCallback( callback(resp); } -static void defaultConnectionCallback(const trantor::TcpConnectionPtr &) { +static void defaultConnectionCallback(const TcpConnectionPtr &) { return; } } // namespace drogon @@ -218,7 +218,7 @@ void HttpServer::onMessage(const TcpConnectionPtr &conn, MsgBuffer *buf) { requestParser->requestImpl()->setPeerAddr(conn->peerAddr()); requestParser->requestImpl()->setLocalAddr(conn->localAddr()); requestParser->requestImpl()->setCreationDate( - trantor::Date::date()); + Date::date()); requestParser->requestImpl()->setSecure( conn->isSSLConnection()); if (requestParser->firstReq() && @@ -457,7 +457,7 @@ void HttpServer::sendResponse(const TcpConnectionPtr &conn, void HttpServer::sendResponses( const TcpConnectionPtr &conn, const std::vector > &responses, - trantor::MsgBuffer &buffer) { + MsgBuffer &buffer) { conn->getLoop()->assertInLoopThread(); if (responses.empty()) return; diff --git a/web_backends/drogon/drogon/lib/src/HttpServer.h b/web_backends/drogon/drogon/lib/src/HttpServer.h index c2729e6..ce6e3a9 100644 --- a/web_backends/drogon/drogon/lib/src/HttpServer.h +++ b/web_backends/drogon/drogon/lib/src/HttpServer.h @@ -23,10 +23,10 @@ #include namespace drogon { -class HttpServer : trantor::NonCopyable { +class HttpServer : NonCopyable { public: - HttpServer(trantor::EventLoop *loop, - const trantor::InetAddress &listenAddr, + HttpServer(EventLoop *loop, + const InetAddress &listenAddr, const std::string &name, const std::vector< std::function > @@ -37,7 +37,7 @@ public: ~HttpServer(); - trantor::EventLoop *getLoop() const { + EventLoop *getLoop() const { return server_.getLoop(); } @@ -48,11 +48,11 @@ public: void setNewWebsocketCallback(const WebSocketNewAsyncCallback &cb) { newWebsocketCallback_ = cb; } - void setConnectionCallback(const trantor::ConnectionCallback &cb) { + void setConnectionCallback(const ConnectionCallback &cb) { connectionCallback_ = cb; } void setIoLoopThreadPool( - const std::shared_ptr &pool) { + const std::shared_ptr &pool) { server_.setIoLoopThreadPool(pool); } void setIoLoopNum(int numThreads) { @@ -61,10 +61,10 @@ public: void kickoffIdleConnections(size_t timeout) { server_.kickoffIdleConnections(timeout); } - trantor::EventLoop *getLoop() { + EventLoop *getLoop() { return server_.getLoop(); } - std::vector getIoLoops() { + std::vector getIoLoops() { return server_.getIoLoops(); } void start(); @@ -78,27 +78,27 @@ public: server_.enableSSL(certPath, keyPath, useOldTLS, sslConfCmds); } - const trantor::InetAddress &address() const { + const InetAddress &address() const { return server_.address(); } private: - void onConnection(const trantor::TcpConnectionPtr &conn); - void onMessage(const trantor::TcpConnectionPtr &, trantor::MsgBuffer *); - void onRequests(const trantor::TcpConnectionPtr &, + void onConnection(const TcpConnectionPtr &conn); + void onMessage(const TcpConnectionPtr &, MsgBuffer *); + void onRequests(const TcpConnectionPtr &, const std::vector &, const std::shared_ptr &); - void sendResponse(const trantor::TcpConnectionPtr &, + void sendResponse(const TcpConnectionPtr &, const HttpResponsePtr &, bool isHeadMethod); void sendResponses( - const trantor::TcpConnectionPtr &conn, + const TcpConnectionPtr &conn, const std::vector > &responses, - trantor::MsgBuffer &buffer); - trantor::TcpServer server_; + MsgBuffer &buffer); + TcpServer server_; HttpAsyncCallback httpAsyncCallback_; WebSocketNewAsyncCallback newWebsocketCallback_; - trantor::ConnectionCallback connectionCallback_; + ConnectionCallback connectionCallback_; const std::vector > &syncAdvices_; const std::vector< diff --git a/web_backends/drogon/drogon/lib/src/ListenerManager.cc b/web_backends/drogon/drogon/lib/src/ListenerManager.cc index 4d8d18f..74adaaf 100644 --- a/web_backends/drogon/drogon/lib/src/ListenerManager.cc +++ b/web_backends/drogon/drogon/lib/src/ListenerManager.cc @@ -28,7 +28,7 @@ namespace drogon { #ifndef _WIN32 -class DrogonFileLocker : public trantor::NonCopyable { +class DrogonFileLocker : public NonCopyable { public: DrogonFileLocker() { fd_ = open("/tmp/drogon.lock", O_TRUNC | O_CREAT, 0666); @@ -45,7 +45,7 @@ private: #endif } // namespace drogon -using namespace trantor; + using namespace drogon; void ListenerManager::addListener( @@ -65,7 +65,7 @@ void ListenerManager::addListener( ip, port, useSSL, certFile, keyFile, useOldTLS, sslConfCmds); } -std::vector ListenerManager::createListeners(trantor::EventLoop *event_loop, +std::vector ListenerManager::createListeners(EventLoop *event_loop, const HttpAsyncCallback &httpCallback, const WebSocketNewAsyncCallback &webSocketCallback, const ConnectionCallback &connectionCallback, @@ -224,7 +224,7 @@ void ListenerManager::startListening() { } } -trantor::EventLoop *ListenerManager::getIOLoop(size_t id) const { +EventLoop *ListenerManager::getIOLoop(size_t id) const { auto const n = listeningloopThreads_.size(); if (0 == n) { LOG_WARN << "Please call getIOLoop() after drogon::app().run()"; @@ -275,8 +275,8 @@ void ListenerManager::stopListening() { #endif } -std::vector ListenerManager::getListeners() const { - std::vector listeners; +std::vector ListenerManager::getListeners() const { + std::vector listeners; for (auto &server : servers_) { listeners.emplace_back(server->address()); } diff --git a/web_backends/drogon/drogon/lib/src/ListenerManager.h b/web_backends/drogon/drogon/lib/src/ListenerManager.h index 8ff2ee7..5185d5d 100644 --- a/web_backends/drogon/drogon/lib/src/ListenerManager.h +++ b/web_backends/drogon/drogon/lib/src/ListenerManager.h @@ -21,11 +21,11 @@ #include #include #include -namespace trantor { + class InetAddress; -} + namespace drogon { -class ListenerManager : public trantor::NonCopyable { +class ListenerManager : public NonCopyable { public: void addListener(const std::string &ip, uint16_t port, @@ -35,10 +35,10 @@ public: bool useOldTLS = false, const std::vector > &sslConfCmds = {}); - std::vector createListeners(trantor::EventLoop *event_loop, + std::vector createListeners(EventLoop *event_loop, const HttpAsyncCallback &httpCallback, const WebSocketNewAsyncCallback &webSocketCallback, - const trantor::ConnectionCallback &connectionCallback, + const ConnectionCallback &connectionCallback, size_t connectionTimeout, const std::string &globalCertFile, const std::string &globalKeyFile, @@ -51,12 +51,12 @@ public: const HttpResponsePtr &)> > &preSendingAdvices); void startListening(); - std::vector getListeners() const; + std::vector getListeners() const; ~ListenerManager() = default; - trantor::EventLoop *getIOLoop(size_t id) const; + EventLoop *getIOLoop(size_t id) const; void stopListening(); - std::vector ioLoops_; + std::vector ioLoops_; private: struct ListenerInfo { @@ -86,9 +86,9 @@ private: }; std::vector listeners_; std::vector > servers_; - std::vector > + std::vector > listeningloopThreads_; - std::shared_ptr ioLoopThreadPoolPtr_; + std::shared_ptr ioLoopThreadPoolPtr_; }; } // namespace drogon diff --git a/web_backends/drogon/drogon/lib/src/PluginsManager.h b/web_backends/drogon/drogon/lib/src/PluginsManager.h index e49aa50..be5a137 100644 --- a/web_backends/drogon/drogon/lib/src/PluginsManager.h +++ b/web_backends/drogon/drogon/lib/src/PluginsManager.h @@ -19,7 +19,7 @@ namespace drogon { using PluginBasePtr = std::unique_ptr; -class PluginsManager : trantor::NonCopyable { +class PluginsManager : NonCopyable { public: void initializeAllPlugins( const Json::Value &configs, diff --git a/web_backends/drogon/drogon/lib/src/SharedLibManager.h b/web_backends/drogon/drogon/lib/src/SharedLibManager.h index 5299755..f339f7b 100644 --- a/web_backends/drogon/drogon/lib/src/SharedLibManager.h +++ b/web_backends/drogon/drogon/lib/src/SharedLibManager.h @@ -38,7 +38,7 @@ #endif namespace drogon { -class SharedLibManager : public trantor::NonCopyable { +class SharedLibManager : public NonCopyable { public: SharedLibManager(const std::vector &libPaths, const std::string &outputPath); @@ -57,7 +57,7 @@ private: void *loadLib(const std::string &soFile, void *oldHld); bool shouldCompileLib(const std::string &soFile, const struct stat &sourceStat); - trantor::TimerId timeId_; - trantor::EventLoopThread workingThread_; + TimerId timeId_; + EventLoopThread workingThread_; }; } // namespace drogon diff --git a/web_backends/drogon/drogon/lib/src/StaticFileRouter.cc b/web_backends/drogon/drogon/lib/src/StaticFileRouter.cc index 6749ae4..d962dd8 100644 --- a/web_backends/drogon/drogon/lib/src/StaticFileRouter.cc +++ b/web_backends/drogon/drogon/lib/src/StaticFileRouter.cc @@ -31,7 +31,7 @@ using namespace drogon; -void StaticFileRouter::init(const std::vector &ioloops) { +void StaticFileRouter::init(const std::vector &ioloops) { // Max timeout up to about 70 days; staticFilesCacheMap_ = decltype(staticFilesCacheMap_)( new IOThreadStorage > >); diff --git a/web_backends/drogon/drogon/lib/src/StaticFileRouter.h b/web_backends/drogon/drogon/lib/src/StaticFileRouter.h index 92f68e0..bc9e477 100644 --- a/web_backends/drogon/drogon/lib/src/StaticFileRouter.h +++ b/web_backends/drogon/drogon/lib/src/StaticFileRouter.h @@ -40,7 +40,7 @@ public: void setBrStatic(bool useBrStatic) { brStaticFlag_ = useBrStatic; } - void init(const std::vector &ioloops); + void init(const std::vector &ioloops); void sendStaticFileResponse( const std::string &filePath, diff --git a/web_backends/drogon/drogon/lib/src/TaskTimeoutFlag.cc b/web_backends/drogon/drogon/lib/src/TaskTimeoutFlag.cc index a51e2ec..232ff5d 100644 --- a/web_backends/drogon/drogon/lib/src/TaskTimeoutFlag.cc +++ b/web_backends/drogon/drogon/lib/src/TaskTimeoutFlag.cc @@ -15,7 +15,7 @@ #include "TaskTimeoutFlag.h" using namespace drogon; -TaskTimeoutFlag::TaskTimeoutFlag(trantor::EventLoop *loop, +TaskTimeoutFlag::TaskTimeoutFlag(EventLoop *loop, const std::chrono::duration &timeout, std::function timeoutCallback) : loop_(loop), timeout_(timeout), timeoutFunc_(timeoutCallback) { diff --git a/web_backends/drogon/drogon/lib/src/TaskTimeoutFlag.h b/web_backends/drogon/drogon/lib/src/TaskTimeoutFlag.h index 4ff4291..c4cbf13 100644 --- a/web_backends/drogon/drogon/lib/src/TaskTimeoutFlag.h +++ b/web_backends/drogon/drogon/lib/src/TaskTimeoutFlag.h @@ -19,10 +19,10 @@ #include namespace drogon { -class TaskTimeoutFlag : public trantor::NonCopyable, +class TaskTimeoutFlag : public NonCopyable, public std::enable_shared_from_this { public: - TaskTimeoutFlag(trantor::EventLoop *loop, + TaskTimeoutFlag(EventLoop *loop, const std::chrono::duration &timeout, std::function timeoutCallback); bool done(); @@ -30,7 +30,7 @@ public: private: std::atomic isDone_{ false }; - trantor::EventLoop *loop_; + EventLoop *loop_; std::chrono::duration timeout_; std::function timeoutFunc_; }; diff --git a/web_backends/drogon/drogon/lib/src/Utilities.cc b/web_backends/drogon/drogon/lib/src/Utilities.cc index 8603c07..1727120 100644 --- a/web_backends/drogon/drogon/lib/src/Utilities.cc +++ b/web_backends/drogon/drogon/lib/src/Utilities.cc @@ -838,7 +838,7 @@ std::string gzipDecompress(const char *data, const size_t ndata) { } } -char *getHttpFullDate(const trantor::Date &date) { +char *getHttpFullDate(const Date &date) { static thread_local int64_t lastSecond = 0; static thread_local char lastTimeString[128] = { 0 }; auto nowSecond = date.microSecondsSinceEpoch() / MICRO_SECONDS_PRE_SEC; @@ -851,7 +851,7 @@ char *getHttpFullDate(const trantor::Date &date) { sizeof(lastTimeString)); return lastTimeString; } -trantor::Date getHttpDate(const std::string &httpFullDateString) { +Date getHttpDate(const std::string &httpFullDateString) { static const std::array formats = { // RFC822 (default) "%a, %d %b %Y %H:%M:%S", @@ -866,11 +866,11 @@ trantor::Date getHttpDate(const std::string &httpFullDateString) { for (const char *format : formats) { if (strptime(httpFullDateString.c_str(), format, &tmptm) != NULL) { auto epoch = timegm(&tmptm); - return trantor::Date(epoch * MICRO_SECONDS_PRE_SEC); + return Date(epoch * MICRO_SECONDS_PRE_SEC); } } LOG_WARN << "invalid datetime format: '" << httpFullDateString << "'"; - return trantor::Date((std::numeric_limits::max)()); + return Date((std::numeric_limits::max)()); } std::string formattedString(const char *format, ...) { std::string strBuffer(128, 0); diff --git a/web_backends/drogon/drogon/lib/src/WebSocketClientImpl.cc b/web_backends/drogon/drogon/lib/src/WebSocketClientImpl.cc index 6afe499..3723ef5 100644 --- a/web_backends/drogon/drogon/lib/src/WebSocketClientImpl.cc +++ b/web_backends/drogon/drogon/lib/src/WebSocketClientImpl.cc @@ -29,7 +29,7 @@ #endif using namespace drogon; -using namespace trantor; + WebSocketClientImpl::~WebSocketClientImpl() { } @@ -39,7 +39,7 @@ WebSocketConnectionPtr WebSocketClientImpl::getConnection() { void WebSocketClientImpl::createTcpClient() { LOG_TRACE << "New TcpClient," << serverAddr_.toIpPort(); tcpClientPtr_ = - std::make_shared(loop_, serverAddr_, "httpClient"); + std::make_shared(loop_, serverAddr_, "httpClient"); if (useSSL_) { tcpClientPtr_->enableSSL(useOldTLS_, validateCert_, domain_); } @@ -47,7 +47,7 @@ void WebSocketClientImpl::createTcpClient() { std::weak_ptr weakPtr = thisPtr; tcpClientPtr_->setConnectionCallback( - [weakPtr](const trantor::TcpConnectionPtr &connPtr) { + [weakPtr](const TcpConnectionPtr &connPtr) { auto thisPtr = weakPtr.lock(); if (!thisPtr) return; @@ -74,8 +74,8 @@ void WebSocketClientImpl::createTcpClient() { thisPtr->loop_->runAfter(1.0, [thisPtr]() { thisPtr->reconnect(); }); }); tcpClientPtr_->setMessageCallback( - [weakPtr](const trantor::TcpConnectionPtr &connPtr, - trantor::MsgBuffer *msg) { + [weakPtr](const TcpConnectionPtr &connPtr, + MsgBuffer *msg) { auto thisPtr = weakPtr.lock(); if (thisPtr) { thisPtr->onRecvMessage(connPtr, msg); @@ -124,12 +124,12 @@ void WebSocketClientImpl::connectToServerInLoop() { if (serverAddr_.ipNetEndian() == 0 && !hasIpv6Address && !domain_.empty() && serverAddr_.portNetEndian() != 0) { if (!resolver_) { - resolver_ = trantor::Resolver::newResolver(loop_); + resolver_ = Resolver::newResolver(loop_); } resolver_->resolve( domain_, [thisPtr = shared_from_this(), - hasIpv6Address](const trantor::InetAddress &addr) { + hasIpv6Address](const InetAddress &addr) { thisPtr->loop_->runInLoop([thisPtr, addr, hasIpv6Address]() { auto port = thisPtr->serverAddr_.portNetEndian(); thisPtr->serverAddr_ = addr; @@ -163,15 +163,15 @@ void WebSocketClientImpl::connectToServerInLoop() { } void WebSocketClientImpl::onRecvWsMessage( - const trantor::TcpConnectionPtr &connPtr, - trantor::MsgBuffer *msgBuffer) { + const TcpConnectionPtr &connPtr, + MsgBuffer *msgBuffer) { assert(websockConnPtr_); websockConnPtr_->onNewMessage(connPtr, msgBuffer); } void WebSocketClientImpl::onRecvMessage( - const trantor::TcpConnectionPtr &connPtr, - trantor::MsgBuffer *msgBuffer) { + const TcpConnectionPtr &connPtr, + MsgBuffer *msgBuffer) { if (upgraded_) { onRecvWsMessage(connPtr, msgBuffer); return; @@ -244,8 +244,8 @@ void WebSocketClientImpl::reconnect() { connectToServerInLoop(); } -WebSocketClientImpl::WebSocketClientImpl(trantor::EventLoop *loop, - const trantor::InetAddress &addr, +WebSocketClientImpl::WebSocketClientImpl(EventLoop *loop, + const InetAddress &addr, bool useSSL, bool useOldTLS, bool validateCert) : @@ -256,7 +256,7 @@ WebSocketClientImpl::WebSocketClientImpl(trantor::EventLoop *loop, validateCert_(validateCert) { } -WebSocketClientImpl::WebSocketClientImpl(trantor::EventLoop *loop, +WebSocketClientImpl::WebSocketClientImpl(EventLoop *loop, const std::string &hostString, bool useOldTLS, bool validateCert) : @@ -325,8 +325,8 @@ WebSocketClientImpl::WebSocketClientImpl(trantor::EventLoop *loop, LOG_TRACE << "userSSL=" << useSSL_ << " domain=" << domain_; } -void WebSocketClientImpl::sendReq(const trantor::TcpConnectionPtr &connPtr) { - trantor::MsgBuffer buffer; +void WebSocketClientImpl::sendReq(const TcpConnectionPtr &connPtr) { + MsgBuffer buffer; assert(upgradeRequest_); auto implPtr = static_cast(upgradeRequest_.get()); implPtr->appendToBuffer(&buffer); @@ -356,13 +356,13 @@ void WebSocketClientImpl::connectToServer( WebSocketClientPtr WebSocketClient::newWebSocketClient(const std::string &ip, uint16_t port, bool useSSL, - trantor::EventLoop *loop, + EventLoop *loop, bool useOldTLS, bool validateCert) { bool isIpv6 = ip.find(':') == std::string::npos ? false : true; return std::make_shared( loop == nullptr ? HttpAppFrameworkImpl::instance().getLoop() : loop, - trantor::InetAddress(ip, port, isIpv6), + InetAddress(ip, port, isIpv6), useSSL, useOldTLS, validateCert); @@ -370,7 +370,7 @@ WebSocketClientPtr WebSocketClient::newWebSocketClient(const std::string &ip, WebSocketClientPtr WebSocketClient::newWebSocketClient( const std::string &hostString, - trantor::EventLoop *loop, + EventLoop *loop, bool useOldTLS, bool validateCert) { return std::make_shared( diff --git a/web_backends/drogon/drogon/lib/src/WebSocketClientImpl.h b/web_backends/drogon/drogon/lib/src/WebSocketClientImpl.h index 49e884b..664d632 100644 --- a/web_backends/drogon/drogon/lib/src/WebSocketClientImpl.h +++ b/web_backends/drogon/drogon/lib/src/WebSocketClientImpl.h @@ -47,17 +47,17 @@ public: void connectToServer(const HttpRequestPtr &request, const WebSocketRequestCallback &callback) override; - trantor::EventLoop *getLoop() override { + EventLoop *getLoop() override { return loop_; } - WebSocketClientImpl(trantor::EventLoop *loop, - const trantor::InetAddress &addr, + WebSocketClientImpl(EventLoop *loop, + const InetAddress &addr, bool useSSL = false, bool useOldTLS = false, bool validateCert = true); - WebSocketClientImpl(trantor::EventLoop *loop, + WebSocketClientImpl(EventLoop *loop, const std::string &hostString, bool useOldTLS = false, bool validateCert = true); @@ -65,9 +65,9 @@ public: ~WebSocketClientImpl() override; private: - std::shared_ptr tcpClientPtr_; - trantor::EventLoop *loop_; - trantor::InetAddress serverAddr_; + std::shared_ptr tcpClientPtr_; + EventLoop *loop_; + InetAddress serverAddr_; std::string domain_; bool useSSL_{ false }; bool useOldTLS_{ false }; @@ -89,13 +89,13 @@ private: WebSocketConnectionImplPtr websockConnPtr_; void connectToServerInLoop(); - void sendReq(const trantor::TcpConnectionPtr &connPtr); - void onRecvMessage(const trantor::TcpConnectionPtr &, trantor::MsgBuffer *); - void onRecvWsMessage(const trantor::TcpConnectionPtr &, - trantor::MsgBuffer *); + void sendReq(const TcpConnectionPtr &connPtr); + void onRecvMessage(const TcpConnectionPtr &, MsgBuffer *); + void onRecvWsMessage(const TcpConnectionPtr &, + MsgBuffer *); void reconnect(); void createTcpClient(); - std::shared_ptr resolver_; + std::shared_ptr resolver_; }; } // namespace drogon diff --git a/web_backends/drogon/drogon/lib/src/WebSocketConnectionImpl.cc b/web_backends/drogon/drogon/lib/src/WebSocketConnectionImpl.cc index 2195f9d..abafe7c 100644 --- a/web_backends/drogon/drogon/lib/src/WebSocketConnectionImpl.cc +++ b/web_backends/drogon/drogon/lib/src/WebSocketConnectionImpl.cc @@ -18,7 +18,7 @@ using namespace drogon; WebSocketConnectionImpl::WebSocketConnectionImpl( - const trantor::TcpConnectionPtr &conn, + const TcpConnectionPtr &conn, bool isServer) : tcpConnectionPtr_(conn), localAddr_(conn->localAddr()), @@ -133,10 +133,10 @@ void WebSocketConnectionImpl::send(const std::string &msg, const WebSocketMessageType type) { send(msg.data(), msg.length(), type); } -const trantor::InetAddress &WebSocketConnectionImpl::localAddr() const { +const InetAddress &WebSocketConnectionImpl::localAddr() const { return localAddr_; } -const trantor::InetAddress &WebSocketConnectionImpl::peerAddr() const { +const InetAddress &WebSocketConnectionImpl::peerAddr() const { return peerAddr_; } @@ -189,7 +189,7 @@ void WebSocketConnectionImpl::disablePing() { } } -bool WebSocketMessageParser::parse(trantor::MsgBuffer *buffer) { +bool WebSocketMessageParser::parse(MsgBuffer *buffer) { // According to the rfc6455 gotAll_ = false; if (buffer->readableBytes() >= 2) { @@ -305,8 +305,8 @@ bool WebSocketMessageParser::parse(trantor::MsgBuffer *buffer) { } void WebSocketConnectionImpl::onNewMessage( - const trantor::TcpConnectionPtr &connPtr, - trantor::MsgBuffer *buffer) { + const TcpConnectionPtr &connPtr, + MsgBuffer *buffer) { while (buffer->readableBytes() > 0) { auto success = parser_.parse(buffer); if (success) { @@ -338,7 +338,7 @@ void WebSocketConnectionImpl::onNewMessage( } void WebSocketConnectionImpl::disablePingInLoop() { - if (pingTimerId_ != trantor::InvalidTimerId) { + if (pingTimerId_ != InvalidTimerId) { tcpConnectionPtr_->getLoop()->invalidateTimer(pingTimerId_); } } diff --git a/web_backends/drogon/drogon/lib/src/WebSocketConnectionImpl.h b/web_backends/drogon/drogon/lib/src/WebSocketConnectionImpl.h index aaa61fc..460b36d 100644 --- a/web_backends/drogon/drogon/lib/src/WebSocketConnectionImpl.h +++ b/web_backends/drogon/drogon/lib/src/WebSocketConnectionImpl.h @@ -25,7 +25,7 @@ using WebSocketConnectionImplPtr = std::shared_ptr; class WebSocketMessageParser { public: - bool parse(trantor::MsgBuffer *buffer); + bool parse(MsgBuffer *buffer); bool gotAll(std::string &message, WebSocketMessageType &type) { assert(message.empty()); if (!gotAll_) @@ -44,9 +44,9 @@ private: class WebSocketConnectionImpl final : public WebSocketConnection, public std::enable_shared_from_this, - public trantor::NonCopyable { + public NonCopyable { public: - explicit WebSocketConnectionImpl(const trantor::TcpConnectionPtr &conn, + explicit WebSocketConnectionImpl(const TcpConnectionPtr &conn, bool isServer = true); ~WebSocketConnectionImpl() override; @@ -58,8 +58,8 @@ public: const std::string &msg, const WebSocketMessageType type = WebSocketMessageType::Text) override; - const trantor::InetAddress &localAddr() const override; - const trantor::InetAddress &peerAddr() const override; + const InetAddress &localAddr() const override; + const InetAddress &peerAddr() const override; bool connected() const override; bool disconnected() const override; @@ -85,22 +85,22 @@ public: closeCallback_ = callback; } - void onNewMessage(const trantor::TcpConnectionPtr &connPtr, - trantor::MsgBuffer *buffer); + void onNewMessage(const TcpConnectionPtr &connPtr, + MsgBuffer *buffer); void onClose() { - if (pingTimerId_ != trantor::InvalidTimerId) + if (pingTimerId_ != InvalidTimerId) tcpConnectionPtr_->getLoop()->invalidateTimer(pingTimerId_); closeCallback_(shared_from_this()); } private: - trantor::TcpConnectionPtr tcpConnectionPtr_; - trantor::InetAddress localAddr_; - trantor::InetAddress peerAddr_; + TcpConnectionPtr tcpConnectionPtr_; + InetAddress localAddr_; + InetAddress peerAddr_; bool isServer_{ true }; WebSocketMessageParser parser_; - trantor::TimerId pingTimerId_{ trantor::InvalidTimerId }; + TimerId pingTimerId_{ InvalidTimerId }; std::vector masks_; std::atomic usingMask_; diff --git a/web_backends/drogon/drogon/lib/src/WebsocketControllersRouter.h b/web_backends/drogon/drogon/lib/src/WebsocketControllersRouter.h index 4e4293d..88a4279 100644 --- a/web_backends/drogon/drogon/lib/src/WebsocketControllersRouter.h +++ b/web_backends/drogon/drogon/lib/src/WebsocketControllersRouter.h @@ -28,7 +28,7 @@ namespace drogon { class HttpAppFrameworkImpl; -class WebsocketControllersRouter : public trantor::NonCopyable { +class WebsocketControllersRouter : public NonCopyable { public: WebsocketControllersRouter( const std::vector; class Resolver; -} // namespace trantor + namespace drogon { using HttpAsyncCallback = diff --git a/web_backends/drogon/drogon/lib/tests/integration_test/client/main.cc b/web_backends/drogon/drogon/lib/tests/integration_test/client/main.cc index 402e600..e01d837 100644 --- a/web_backends/drogon/drogon/lib/tests/integration_test/client/main.cc +++ b/web_backends/drogon/drogon/lib/tests/integration_test/client/main.cc @@ -889,7 +889,7 @@ DROGON_TEST(HttpsTest) { } int main(int argc, char **argv) { - trantor::Logger::setLogLevel(trantor::Logger::LogLevel::kDebug); + Logger::setLogLevel(Logger::LogLevel::kDebug); loadFileLengths(); std::promise p1; diff --git a/web_backends/drogon/drogon/lib/tests/integration_test/server/PipeliningTest.cc b/web_backends/drogon/drogon/lib/tests/integration_test/server/PipeliningTest.cc index 09ed3bd..dd82e18 100644 --- a/web_backends/drogon/drogon/lib/tests/integration_test/server/PipeliningTest.cc +++ b/web_backends/drogon/drogon/lib/tests/integration_test/server/PipeliningTest.cc @@ -27,7 +27,7 @@ void PipeliningTest::asyncHandleHttpRequest( }); return; } - trantor::EventLoop::getEventLoopOfCurrentThread()->runAfter( + EventLoop::getEventLoopOfCurrentThread()->runAfter( delay, [c, callback]() { auto resp = HttpResponse::newHttpResponse(); auto str = utils::formattedString("

the %dth response

", c); diff --git a/web_backends/drogon/drogon/lib/tests/integration_test/server/TimeFilter.cc b/web_backends/drogon/drogon/lib/tests/integration_test/server/TimeFilter.cc index b6d7074..7055ee8 100644 --- a/web_backends/drogon/drogon/lib/tests/integration_test/server/TimeFilter.cc +++ b/web_backends/drogon/drogon/lib/tests/integration_test/server/TimeFilter.cc @@ -7,18 +7,18 @@ void TimeFilter::doFilter(const HttpRequestPtr &req, FilterCallback &&cb, FilterChainCallback &&ccb) { - trantor::Date now = trantor::Date::date(); + Date now = Date::date(); if (!req->session()) { // no session support by framework,pls enable session auto resp = HttpResponse::newNotFoundResponse(); cb(resp); return; } - auto lastDate = req->session()->getOptional(VDate); + auto lastDate = req->session()->getOptional(VDate); if (lastDate) { LOG_TRACE << "last:" << lastDate->toFormattedString(false); - req->session()->modify(VDate, - [now](trantor::Date &vdate) { + req->session()->modify(VDate, + [now](Date &vdate) { vdate = now; }); LOG_TRACE << "update visitDate"; diff --git a/web_backends/drogon/drogon/lib/tests/integration_test/server/a-directory/page.html b/web_backends/drogon/drogon/lib/tests/integration_test/server/a-directory/page.html index e1b1fc5..1e1919d 100644 --- a/web_backends/drogon/drogon/lib/tests/integration_test/server/a-directory/page.html +++ b/web_backends/drogon/drogon/lib/tests/integration_test/server/a-directory/page.html @@ -1,11 +1,11 @@

Build Status -Codacy Badge -Total alerts -Language grade: C/C++ -Join the chat at https://gitter.im/drogon-web/community -Docker image

+ Codacy Badge + Total alerts + Language grade: C/C++ + Join the chat at https://gitter.im/drogon-web/community + Docker image

Overview (from an implicit page)

Drogon is a C++14/17-based HTTP application framework. Drogon can be used to easily build various types of web application server programs using C++. Drogon is the name of a dragon in the American TV series “Game of Thrones” that I really like.

@@ -13,28 +13,28 @@

Drogon’s main application platform is Linux. It also supports Mac OS and FreeBSD. Currently, it does not support windows. Its main features are as follows:

    -
  • Use a non-blocking I/O network lib based on epoll (kqueue under MacOS/FreeBSD) to provide high-concurrency, high-performance network IO, please visit the benchmarks page for more details;
  • -
  • Provide a completely asynchronous programming mode;
  • -
  • Support Http1.0/1.1 (server side and client side);
  • -
  • Based on template, a simple reflection mechanism is implemented to completely decouple the main program framework, controllers and views.
  • -
  • Support cookies and built-in sessions;
  • -
  • Support back-end rendering, the controller generates the data to the view to generate the Html page, the view is described by a “JSP-like” CSP file, the C++ code is embedded into the Html page by the CSP tag, and the drogon command-line tool automatically generates the C++ code file for compilation;
  • -
  • Support view page dynamic loading (dynamic compilation and loading at runtime);
  • -
  • Provide a convenient and flexible routing solution from the path to the controller handler;
  • -
  • Support filter chains to facilitate the execution of unified logic (such as login verification, Http Method constraint verification, etc.) before controllers;
  • -
  • Support https (based on OpenSSL);
  • -
  • Support WebSocket (server side and client side);
  • -
  • Support JSON format request and response, very friendly to the Restful API application development;
  • -
  • Support file download and upload;
  • -
  • Support gzip compression transmission;
  • -
  • Support pipelining;
  • -
  • Provide a lightweight command line tool, drogon_ctl, to simplify the creation of various classes in Drogon and the generation of view code;
  • -
  • Support non-blocking I/O based asynchronously reading and writing database (PostgreSQL and MySQL(MariaDB) database);
  • -
  • Support asynchronously reading and writing sqlite3 database based on thread pool;
  • -
  • Support ARM Architecture;
  • -
  • Provide a convenient lightweight ORM implementation that supports for regular object-to-database bidirectional mapping;
  • -
  • Support plugins which can be installed by the configuration file at load time;
  • -
  • Support AOP with build-in joinpoints.
  • +
  • Use a non-blocking I/O network lib based on epoll (kqueue under MacOS/FreeBSD) to provide high-concurrency, high-performance network IO, please visit the benchmarks page for more details;
  • +
  • Provide a completely asynchronous programming mode;
  • +
  • Support Http1.0/1.1 (server side and client side);
  • +
  • Based on template, a simple reflection mechanism is implemented to completely decouple the main program framework, controllers and views.
  • +
  • Support cookies and built-in sessions;
  • +
  • Support back-end rendering, the controller generates the data to the view to generate the Html page, the view is described by a “JSP-like” CSP file, the C++ code is embedded into the Html page by the CSP tag, and the drogon command-line tool automatically generates the C++ code file for compilation;
  • +
  • Support view page dynamic loading (dynamic compilation and loading at runtime);
  • +
  • Provide a convenient and flexible routing solution from the path to the controller handler;
  • +
  • Support filter chains to facilitate the execution of unified logic (such as login verification, Http Method constraint verification, etc.) before controllers;
  • +
  • Support https (based on OpenSSL);
  • +
  • Support WebSocket (server side and client side);
  • +
  • Support JSON format request and response, very friendly to the Restful API application development;
  • +
  • Support file download and upload;
  • +
  • Support gzip compression transmission;
  • +
  • Support pipelining;
  • +
  • Provide a lightweight command line tool, drogon_ctl, to simplify the creation of various classes in Drogon and the generation of view code;
  • +
  • Support non-blocking I/O based asynchronously reading and writing database (PostgreSQL and MySQL(MariaDB) database);
  • +
  • Support asynchronously reading and writing sqlite3 database based on thread pool;
  • +
  • Support ARM Architecture;
  • +
  • Provide a convenient lightweight ORM implementation that supports for regular object-to-database bidirectional mapping;
  • +
  • Support plugins which can be installed by the configuration file at load time;
  • +
  • Support AOP with build-in joinpoints.

A very simple example

@@ -44,144 +44,146 @@

Below is the main program of a typical drogon application:

c++ -#include <drogon/drogon.h> -using namespace drogon; -int main() -{ - app().setLogPath("./"); - app().setLogLevel(trantor::Logger::kWarn); - app().addListener("0.0.0.0", 80); - app().setThreadNum(16); - app().enableRunAsDaemon(); - app().run(); -} -

+ #include <drogon/drogon.h> + using namespace drogon; + int main() + { + app().setLogPath("./"); + app().setLogLevel(Logger::kWarn); + app().addListener("0.0.0.0", 80); + app().setThreadNum(16); + app().enableRunAsDaemon(); + app().run(); + } +

It can be further simplified by using configuration file as follows:

c++ -#include <drogon/drogon.h> -using namespace drogon; -int main() -{ - app().loadConfigFile("./config.json"); - app().run(); -} -

+ #include <drogon/drogon.h> + using namespace drogon; + int main() + { + app().loadConfigFile("./config.json"); + app().run(); + } +

Drogon provides some interfaces for adding controller logic directly in the main() function, for example, user can register a handler like this in Drogon:

c++ -app.registerHandler("/test?username={1}", - [](const HttpRequestPtr& req, - const std::function<void (const HttpResponsePtr &)> & callback, - const std::string &name) - { - Json::Value json; - json["result"]="ok"; - json["message"]=std::string("hello,")+name; - auto resp=HttpResponse::newHttpJsonResponse(json); - callback(resp); - }, - {Get,"LoginFilter"}); -

+ app.registerHandler("/test?username={1}", + [](const HttpRequestPtr& req, + const std::function<void (const HttpResponsePtr &)> & callback, + const std::string &name) + { + Json::Value json; + json["result"]="ok"; + json["message"]=std::string("hello,")+name; + auto resp=HttpResponse::newHttpJsonResponse(json); + callback(resp); + }, + {Get,"LoginFilter"}); +

While such interfaces look intuitive, they are not suitable for complex business logic scenarios. Assuming there are tens or even hundreds of handlers that need to be registered in the framework, isn’t it a better practice to implement them separately in their respective classes? So unless your logic is very simple, we don’t recommend using above interfaces. Instead, we can create an HttpSimpleController as follows:

```c++ -/// The TestCtrl.h file -#pragma once -#include <drogon/HttpSimpleController.h> -using namespace drogon; -class TestCtrl:public drogon::HttpSimpleController -{ -public: - virtual void asyncHandleHttpRequest(const HttpRequestPtr& req,const std::function<void (const HttpResponsePtr &)> & callback)override; - PATH_LIST_BEGIN - PATH_ADD("/test",Get); - PATH_LIST_END -};

+ /// The TestCtrl.h file + #pragma once + #include <drogon/HttpSimpleController.h> + using namespace drogon; + class TestCtrl:public drogon::HttpSimpleController + { + public: + virtual void asyncHandleHttpRequest(const HttpRequestPtr& req,const std::function<void (const HttpResponsePtr &)> & callback)override; + PATH_LIST_BEGIN + PATH_ADD("/test",Get); + PATH_LIST_END + }; +

/// The TestCtrl.cc file -#include “TestCtrl.h” -void TestCtrl::asyncHandleHttpRequest(const HttpRequestPtr& req, - const std::function<void (const HttpResponsePtr &)> & callback) -{ + #include “TestCtrl.h” + void TestCtrl::asyncHandleHttpRequest(const HttpRequestPtr& req, + const std::function<void (const HttpResponsePtr &)> & callback) + { //write your application logic here auto resp = HttpResponse::newHttpResponse(); resp->setBody(“<p>Hello, world!</p>”); resp->setExpiredTime(0); callback(resp); -} -```

+ } + ```

Most of the above programs can be automatically generated by the command line tool drogon_ctl provided by drogon (The cammand is drogon_ctl create controller TestCtrl). All the user needs to do is add their own business logic. In the example, the controller returns a Hello, world! string when the client accesses the http://ip/test URL.

For JSON format response, we create the controller as follows:

```c++ -/// The header file -#pragma once -#include <drogon/HttpSimpleController.h> -using namespace drogon; -class JsonCtrl : public drogon::HttpSimpleController -{ - public: - virtual void asyncHandleHttpRequest(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback) override; - PATH_LIST_BEGIN - //list path definitions here; - PATH_ADD("/json", Get); - PATH_LIST_END -};

+ /// The header file + #pragma once + #include <drogon/HttpSimpleController.h> + using namespace drogon; + class JsonCtrl : public drogon::HttpSimpleController + { + public: + virtual void asyncHandleHttpRequest(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback) override; + PATH_LIST_BEGIN + //list path definitions here; + PATH_ADD("/json", Get); + PATH_LIST_END + }; +

/// The source file -#include “JsonCtrl.h” -void JsonCtrl::asyncHandleHttpRequest(const HttpRequestPtr &req, - const std::function<void(const HttpResponsePtr &)> &callback) -{ + #include “JsonCtrl.h” + void JsonCtrl::asyncHandleHttpRequest(const HttpRequestPtr &req, + const std::function<void(const HttpResponsePtr &)> &callback) + { Json::Value ret; ret[“message”] = “Hello, World!”; auto resp = HttpResponse::newHttpJsonResponse(ret); callback(resp); -} -```

+ } + ```

Let’s go a step further and create a demo RESTful API with the HttpController class, as shown below (Omit the source file):

c++ -/// The header file -#pragma once -#include <drogon/HttpController.h> -using namespace drogon; -namespace api -{ -namespace v1 -{ -class User : public drogon::HttpController<User> -{ - public: - METHOD_LIST_BEGIN - //use METHOD_ADD to add your custom processing function here; - METHOD_ADD(User::getInfo, "/{1}", Get); //path is /api/v1/User/{arg1} - METHOD_ADD(User::getDetailInfo, "/{1}/detailinfo", Get); //path is /api/v1/User/{arg1}/detailinfo - METHOD_ADD(User::newUser, "/{1}", Post); //path is /api/v1/User/{arg1} - METHOD_LIST_END - //your declaration of processing function maybe like this: - void getInfo(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback, int userId) const; - void getDetailInfo(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback, int userId) const; - void newUser(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback, std::string &&userName); - public: - User() - { + /// The header file + #pragma once + #include <drogon/HttpController.h> + using namespace drogon; + namespace api + { + namespace v1 + { + class User : public drogon::HttpController<User> + { + public: + METHOD_LIST_BEGIN + //use METHOD_ADD to add your custom processing function here; + METHOD_ADD(User::getInfo, "/{1}", Get); //path is /api/v1/User/{arg1} + METHOD_ADD(User::getDetailInfo, "/{1}/detailinfo", Get); //path is /api/v1/User/{arg1}/detailinfo + METHOD_ADD(User::newUser, "/{1}", Post); //path is /api/v1/User/{arg1} + METHOD_LIST_END + //your declaration of processing function maybe like this: + void getInfo(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback, int userId) const; + void getDetailInfo(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback, int userId) const; + void newUser(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback, std::string &&userName); + public: + User() + { LOG_DEBUG << "User constructor!"; - } -}; -} // namespace v1 -} // namespace api -

+ } + }; + } // namespace v1 + } // namespace api +

As you can see, users can use the HttpController to map paths and parameters at the same time. This is a very convenient way to create a RESTful API application.

In addition, you can also find that all handler interfaces are in asynchronous mode, where the response is returned by a callback object. This design is for performance reasons because in asynchronous mode the drogon application can handle a large number of concurrent requests with a small number of threads.

-

After compiling all of the above source files, we get a very simple web application. This is a good start. for more information, please visit the wiki site

+

After compiling all of the above source files, we get a very simple web application. This is a good start. for more information, please visit the wiki site

\ No newline at end of file diff --git a/web_backends/drogon/drogon/lib/tests/integration_test/server/api_v1_CoroTest.cc b/web_backends/drogon/drogon/lib/tests/integration_test/server/api_v1_CoroTest.cc index 352e1ca..fa78999 100644 --- a/web_backends/drogon/drogon/lib/tests/integration_test/server/api_v1_CoroTest.cc +++ b/web_backends/drogon/drogon/lib/tests/integration_test/server/api_v1_CoroTest.cc @@ -5,7 +5,7 @@ Task<> CoroTest::get(HttpRequestPtr req, std::function callback) { // Force co_await to test awaiting works co_await drogon::sleepCoro( - trantor::EventLoop::getEventLoopOfCurrentThread(), + EventLoop::getEventLoopOfCurrentThread(), std::chrono::milliseconds(100)); auto resp = HttpResponse::newHttpResponse(); diff --git a/web_backends/drogon/drogon/lib/tests/integration_test/server/index.html b/web_backends/drogon/drogon/lib/tests/integration_test/server/index.html index c9bb37d..5d019ee 100644 --- a/web_backends/drogon/drogon/lib/tests/integration_test/server/index.html +++ b/web_backends/drogon/drogon/lib/tests/integration_test/server/index.html @@ -1,11 +1,11 @@

Build Status -Codacy Badge -Total alerts -Language grade: C/C++ -Join the chat at https://gitter.im/drogon-web/community -Docker image

+ Codacy Badge + Total alerts + Language grade: C/C++ + Join the chat at https://gitter.im/drogon-web/community + Docker image

Overview

Drogon is a C++14/17-based HTTP application framework. Drogon can be used to easily build various types of web application server programs using C++. Drogon is the name of a dragon in the American TV series “Game of Thrones” that I really like.

@@ -13,28 +13,28 @@

Drogon’s main application platform is Linux. It also supports Mac OS and FreeBSD. Currently, it does not support windows. Its main features are as follows:

    -
  • Use a non-blocking I/O network lib based on epoll (kqueue under MacOS/FreeBSD) to provide high-concurrency, high-performance network IO, please visit the benchmarks page for more details;
  • -
  • Provide a completely asynchronous programming mode;
  • -
  • Support Http1.0/1.1 (server side and client side);
  • -
  • Based on template, a simple reflection mechanism is implemented to completely decouple the main program framework, controllers and views.
  • -
  • Support cookies and built-in sessions;
  • -
  • Support back-end rendering, the controller generates the data to the view to generate the Html page, the view is described by a “JSP-like” CSP file, the C++ code is embedded into the Html page by the CSP tag, and the drogon command-line tool automatically generates the C++ code file for compilation;
  • -
  • Support view page dynamic loading (dynamic compilation and loading at runtime);
  • -
  • Provide a convenient and flexible routing solution from the path to the controller handler;
  • -
  • Support filter chains to facilitate the execution of unified logic (such as login verification, Http Method constraint verification, etc.) before controllers;
  • -
  • Support https (based on OpenSSL);
  • -
  • Support WebSocket (server side and client side);
  • -
  • Support JSON format request and response, very friendly to the Restful API application development;
  • -
  • Support file download and upload;
  • -
  • Support gzip compression transmission;
  • -
  • Support pipelining;
  • -
  • Provide a lightweight command line tool, drogon_ctl, to simplify the creation of various classes in Drogon and the generation of view code;
  • -
  • Support non-blocking I/O based asynchronously reading and writing database (PostgreSQL and MySQL(MariaDB) database);
  • -
  • Support asynchronously reading and writing sqlite3 database based on thread pool;
  • -
  • Support ARM Architecture;
  • -
  • Provide a convenient lightweight ORM implementation that supports for regular object-to-database bidirectional mapping;
  • -
  • Support plugins which can be installed by the configuration file at load time;
  • -
  • Support AOP with build-in joinpoints.
  • +
  • Use a non-blocking I/O network lib based on epoll (kqueue under MacOS/FreeBSD) to provide high-concurrency, high-performance network IO, please visit the benchmarks page for more details;
  • +
  • Provide a completely asynchronous programming mode;
  • +
  • Support Http1.0/1.1 (server side and client side);
  • +
  • Based on template, a simple reflection mechanism is implemented to completely decouple the main program framework, controllers and views.
  • +
  • Support cookies and built-in sessions;
  • +
  • Support back-end rendering, the controller generates the data to the view to generate the Html page, the view is described by a “JSP-like” CSP file, the C++ code is embedded into the Html page by the CSP tag, and the drogon command-line tool automatically generates the C++ code file for compilation;
  • +
  • Support view page dynamic loading (dynamic compilation and loading at runtime);
  • +
  • Provide a convenient and flexible routing solution from the path to the controller handler;
  • +
  • Support filter chains to facilitate the execution of unified logic (such as login verification, Http Method constraint verification, etc.) before controllers;
  • +
  • Support https (based on OpenSSL);
  • +
  • Support WebSocket (server side and client side);
  • +
  • Support JSON format request and response, very friendly to the Restful API application development;
  • +
  • Support file download and upload;
  • +
  • Support gzip compression transmission;
  • +
  • Support pipelining;
  • +
  • Provide a lightweight command line tool, drogon_ctl, to simplify the creation of various classes in Drogon and the generation of view code;
  • +
  • Support non-blocking I/O based asynchronously reading and writing database (PostgreSQL and MySQL(MariaDB) database);
  • +
  • Support asynchronously reading and writing sqlite3 database based on thread pool;
  • +
  • Support ARM Architecture;
  • +
  • Provide a convenient lightweight ORM implementation that supports for regular object-to-database bidirectional mapping;
  • +
  • Support plugins which can be installed by the configuration file at load time;
  • +
  • Support AOP with build-in joinpoints.

A very simple example

@@ -44,144 +44,146 @@

Below is the main program of a typical drogon application:

c++ -#include <drogon/drogon.h> -using namespace drogon; -int main() -{ - app().setLogPath("./"); - app().setLogLevel(trantor::Logger::kWarn); - app().addListener("0.0.0.0", 80); - app().setThreadNum(16); - app().enableRunAsDaemon(); - app().run(); -} -

+ #include <drogon/drogon.h> + using namespace drogon; + int main() + { + app().setLogPath("./"); + app().setLogLevel(Logger::kWarn); + app().addListener("0.0.0.0", 80); + app().setThreadNum(16); + app().enableRunAsDaemon(); + app().run(); + } +

It can be further simplified by using configuration file as follows:

c++ -#include <drogon/drogon.h> -using namespace drogon; -int main() -{ - app().loadConfigFile("./config.json"); - app().run(); -} -

+ #include <drogon/drogon.h> + using namespace drogon; + int main() + { + app().loadConfigFile("./config.json"); + app().run(); + } +

Drogon provides some interfaces for adding controller logic directly in the main() function, for example, user can register a handler like this in Drogon:

c++ -app.registerHandler("/test?username={1}", - [](const HttpRequestPtr& req, - const std::function<void (const HttpResponsePtr &)> & callback, - const std::string &name) - { - Json::Value json; - json["result"]="ok"; - json["message"]=std::string("hello,")+name; - auto resp=HttpResponse::newHttpJsonResponse(json); - callback(resp); - }, - {Get,"LoginFilter"}); -

+ app.registerHandler("/test?username={1}", + [](const HttpRequestPtr& req, + const std::function<void (const HttpResponsePtr &)> & callback, + const std::string &name) + { + Json::Value json; + json["result"]="ok"; + json["message"]=std::string("hello,")+name; + auto resp=HttpResponse::newHttpJsonResponse(json); + callback(resp); + }, + {Get,"LoginFilter"}); +

While such interfaces look intuitive, they are not suitable for complex business logic scenarios. Assuming there are tens or even hundreds of handlers that need to be registered in the framework, isn’t it a better practice to implement them separately in their respective classes? So unless your logic is very simple, we don’t recommend using above interfaces. Instead, we can create an HttpSimpleController as follows:

```c++ -/// The TestCtrl.h file -#pragma once -#include <drogon/HttpSimpleController.h> -using namespace drogon; -class TestCtrl:public drogon::HttpSimpleController -{ -public: - virtual void asyncHandleHttpRequest(const HttpRequestPtr& req,const std::function<void (const HttpResponsePtr &)> & callback)override; - PATH_LIST_BEGIN - PATH_ADD("/test",Get); - PATH_LIST_END -};

+ /// The TestCtrl.h file + #pragma once + #include <drogon/HttpSimpleController.h> + using namespace drogon; + class TestCtrl:public drogon::HttpSimpleController + { + public: + virtual void asyncHandleHttpRequest(const HttpRequestPtr& req,const std::function<void (const HttpResponsePtr &)> & callback)override; + PATH_LIST_BEGIN + PATH_ADD("/test",Get); + PATH_LIST_END + }; +

/// The TestCtrl.cc file -#include “TestCtrl.h” -void TestCtrl::asyncHandleHttpRequest(const HttpRequestPtr& req, - const std::function<void (const HttpResponsePtr &)> & callback) -{ + #include “TestCtrl.h” + void TestCtrl::asyncHandleHttpRequest(const HttpRequestPtr& req, + const std::function<void (const HttpResponsePtr &)> & callback) + { //write your application logic here auto resp = HttpResponse::newHttpResponse(); resp->setBody(“<p>Hello, world!</p>”); resp->setExpiredTime(0); callback(resp); -} -```

+ } + ```

Most of the above programs can be automatically generated by the command line tool drogon_ctl provided by drogon (The cammand is drogon_ctl create controller TestCtrl). All the user needs to do is add their own business logic. In the example, the controller returns a Hello, world! string when the client accesses the http://ip/test URL.

For JSON format response, we create the controller as follows:

```c++ -/// The header file -#pragma once -#include <drogon/HttpSimpleController.h> -using namespace drogon; -class JsonCtrl : public drogon::HttpSimpleController -{ - public: - virtual void asyncHandleHttpRequest(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback) override; - PATH_LIST_BEGIN - //list path definitions here; - PATH_ADD("/json", Get); - PATH_LIST_END -};

+ /// The header file + #pragma once + #include <drogon/HttpSimpleController.h> + using namespace drogon; + class JsonCtrl : public drogon::HttpSimpleController + { + public: + virtual void asyncHandleHttpRequest(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback) override; + PATH_LIST_BEGIN + //list path definitions here; + PATH_ADD("/json", Get); + PATH_LIST_END + }; +

/// The source file -#include “JsonCtrl.h” -void JsonCtrl::asyncHandleHttpRequest(const HttpRequestPtr &req, - const std::function<void(const HttpResponsePtr &)> &callback) -{ + #include “JsonCtrl.h” + void JsonCtrl::asyncHandleHttpRequest(const HttpRequestPtr &req, + const std::function<void(const HttpResponsePtr &)> &callback) + { Json::Value ret; ret[“message”] = “Hello, World!”; auto resp = HttpResponse::newHttpJsonResponse(ret); callback(resp); -} -```

+ } + ```

Let’s go a step further and create a demo RESTful API with the HttpController class, as shown below (Omit the source file):

c++ -/// The header file -#pragma once -#include <drogon/HttpController.h> -using namespace drogon; -namespace api -{ -namespace v1 -{ -class User : public drogon::HttpController<User> -{ - public: - METHOD_LIST_BEGIN - //use METHOD_ADD to add your custom processing function here; - METHOD_ADD(User::getInfo, "/{1}", Get); //path is /api/v1/User/{arg1} - METHOD_ADD(User::getDetailInfo, "/{1}/detailinfo", Get); //path is /api/v1/User/{arg1}/detailinfo - METHOD_ADD(User::newUser, "/{1}", Post); //path is /api/v1/User/{arg1} - METHOD_LIST_END - //your declaration of processing function maybe like this: - void getInfo(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback, int userId) const; - void getDetailInfo(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback, int userId) const; - void newUser(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback, std::string &&userName); - public: - User() - { + /// The header file + #pragma once + #include <drogon/HttpController.h> + using namespace drogon; + namespace api + { + namespace v1 + { + class User : public drogon::HttpController<User> + { + public: + METHOD_LIST_BEGIN + //use METHOD_ADD to add your custom processing function here; + METHOD_ADD(User::getInfo, "/{1}", Get); //path is /api/v1/User/{arg1} + METHOD_ADD(User::getDetailInfo, "/{1}/detailinfo", Get); //path is /api/v1/User/{arg1}/detailinfo + METHOD_ADD(User::newUser, "/{1}", Post); //path is /api/v1/User/{arg1} + METHOD_LIST_END + //your declaration of processing function maybe like this: + void getInfo(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback, int userId) const; + void getDetailInfo(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback, int userId) const; + void newUser(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback, std::string &&userName); + public: + User() + { LOG_DEBUG << "User constructor!"; - } -}; -} // namespace v1 -} // namespace api -

+ } + }; + } // namespace v1 + } // namespace api +

As you can see, users can use the HttpController to map paths and parameters at the same time. This is a very convenient way to create a RESTful API application.

In addition, you can also find that all handler interfaces are in asynchronous mode, where the response is returned by a callback object. This design is for performance reasons because in asynchronous mode the drogon application can handle a large number of concurrent requests with a small number of threads.

-

After compiling all of the above source files, we get a very simple web application. This is a good start. for more information, please visit the wiki site

+

After compiling all of the above source files, we get a very simple web application. This is a good start. for more information, please visit the wiki site

\ No newline at end of file diff --git a/web_backends/drogon/drogon/lib/tests/integration_test/server/main.cc b/web_backends/drogon/drogon/lib/tests/integration_test/server/main.cc index dc0e728..9a7dfc4 100644 --- a/web_backends/drogon/drogon/lib/tests/integration_test/server/main.cc +++ b/web_backends/drogon/drogon/lib/tests/integration_test/server/main.cc @@ -240,8 +240,8 @@ int main() { // AOP example app().registerBeginningAdvice( []() { LOG_DEBUG << "Event loop is running!"; }); - app().registerNewConnectionAdvice([](const trantor::InetAddress &peer, - const trantor::InetAddress &local) { + app().registerNewConnectionAdvice([](const InetAddress &peer, + const InetAddress &local) { LOG_DEBUG << "New connection: " << peer.toIpPort() << "-->" << local.toIpPort(); return true; @@ -336,7 +336,7 @@ int main() { }); std::cout << "Date: " << std::string{ drogon::utils::getHttpFullDate( - trantor::Date::now()) } + Date::now()) } << std::endl; app().run(); } diff --git a/web_backends/drogon/drogon/lib/tests/unittests/CacheMapTest.cc b/web_backends/drogon/drogon/lib/tests/unittests/CacheMapTest.cc index a9b3308..05d321b 100644 --- a/web_backends/drogon/drogon/lib/tests/unittests/CacheMapTest.cc +++ b/web_backends/drogon/drogon/lib/tests/unittests/CacheMapTest.cc @@ -9,7 +9,7 @@ using namespace drogon; using namespace std::chrono_literals; DROGON_TEST(CacheMapTest) { - trantor::EventLoopThread loopThread; + EventLoopThread loopThread; loopThread.run(); drogon::CacheMap cache(loopThread.getLoop(), 0.1, diff --git a/web_backends/drogon/drogon/lib/tests/unittests/CookieTest.cc b/web_backends/drogon/drogon/lib/tests/unittests/CookieTest.cc index 31f75fc..b4308c0 100644 --- a/web_backends/drogon/drogon/lib/tests/unittests/CookieTest.cc +++ b/web_backends/drogon/drogon/lib/tests/unittests/CookieTest.cc @@ -11,7 +11,7 @@ DROGON_TEST(CookieTest) { drogon::Cookie cookie3("test", "3"); cookie3.setDomain("drogon.org"); - cookie3.setExpiresDate(trantor::Date(1621561557000000L)); + cookie3.setExpiresDate(Date(1621561557000000L)); CHECK(cookie3.cookieString() == "Set-Cookie: test=3; Expires=Fri, 21 May 2021 01:45:57 GMT; " "Domain=drogon.org; HttpOnly\r\n"); diff --git a/web_backends/drogon/drogon/lib/tests/unittests/MsgBufferTest.cc b/web_backends/drogon/drogon/lib/tests/unittests/MsgBufferTest.cc index be3da42..1b3977b 100644 --- a/web_backends/drogon/drogon/lib/tests/unittests/MsgBufferTest.cc +++ b/web_backends/drogon/drogon/lib/tests/unittests/MsgBufferTest.cc @@ -3,7 +3,7 @@ #include #include -using namespace trantor; + DROGON_TEST(MsgBufferTest) { SUBSECTION(readableTest) { MsgBuffer buffer; diff --git a/web_backends/drogon/drogon/lib/tests/unittests/main.cc b/web_backends/drogon/drogon/lib/tests/unittests/main.cc index ad4ea66..48a75a5 100644 --- a/web_backends/drogon/drogon/lib/tests/unittests/main.cc +++ b/web_backends/drogon/drogon/lib/tests/unittests/main.cc @@ -3,7 +3,7 @@ #include using namespace drogon; -using namespace trantor; + DROGON_TEST(TestFrameworkSelfTest) { CHECK(TEST_CTX->name() == "TestFrameworkSelfTest"); diff --git a/web_backends/drogon/drogon_web_server.cpp b/web_backends/drogon/drogon_web_server.cpp index a0ecb7b..18b7d30 100644 --- a/web_backends/drogon/drogon_web_server.cpp +++ b/web_backends/drogon/drogon_web_server.cpp @@ -59,7 +59,7 @@ void DrogonWebServer::run() { LOG_TRACE << "Start to run..."; - trantor::AsyncFileLogger asyncFileLogger; + AsyncFileLogger asyncFileLogger; // Create dirs for cache files for (int i = 0; i < 256; ++i) { @@ -127,7 +127,7 @@ void DrogonWebServer::run() { asyncFileLogger.setFileName(baseName, ".log", _log_path); asyncFileLogger.startLogging(); - trantor::Logger::setOutputFunction( + Logger::setOutputFunction( [&](const char *msg, const uint64_t len) { asyncFileLogger.output(msg, len); }, @@ -240,8 +240,8 @@ const std::string &DrogonWebServer::get_upload_path() const { return _upload_path; } -const std::shared_ptr &DrogonWebServer::get_resolver() const { - static std::shared_ptr resolver = trantor::Resolver::newResolver(get_loop()); +const std::shared_ptr &DrogonWebServer::get_resolver() const { + static std::shared_ptr resolver = Resolver::newResolver(get_loop()); return resolver; } @@ -286,8 +286,8 @@ void DrogonWebServer::set_log_path(const std::string &logPath, const std::string _logfile_base_name = logfileBaseName; _logfile_size = logfileSize; } -void DrogonWebServer::set_log_level(trantor::Logger::LogLevel level) { - trantor::Logger::setLogLevel(level); +void DrogonWebServer::set_log_level(Logger::LogLevel level) { + Logger::setLogLevel(level); } void DrogonWebServer::enable_sendfile(bool sendFile) { @@ -405,10 +405,10 @@ const std::pair &DrogonWebServer::get_float_precision return _float_precision_in_json; } -trantor::EventLoop *DrogonWebServer::get_loop() const { +EventLoop *DrogonWebServer::get_loop() const { return _loop; } -trantor::EventLoop *DrogonWebServer::get_io_loop(size_t id) const { +EventLoop *DrogonWebServer::get_io_loop(size_t id) const { assert(_listener_manager); return _listener_manager->getIOLoop(id); @@ -438,7 +438,7 @@ const std::string &DrogonWebServer::get_server_header_string() const { return _server_header; } -std::vector DrogonWebServer::get_listeners() const { +std::vector DrogonWebServer::get_listeners() const { return _listener_manager->getListeners(); } @@ -454,7 +454,7 @@ bool DrogonWebServer::support_ssl() const { } size_t DrogonWebServer::get_current_thread_index() const { - trantor::EventLoop *loop = trantor::EventLoop::getEventLoopOfCurrentThread(); + EventLoop *loop = EventLoop::getEventLoopOfCurrentThread(); if (loop) { return loop->index(); @@ -565,7 +565,7 @@ void DrogonWebServer::on_new_websock_request(const HttpRequestImplPtr &req, std: }); }*/ } -void DrogonWebServer::on_connection(const trantor::TcpConnectionPtr &conn) { +void DrogonWebServer::on_connection(const TcpConnectionPtr &conn) { static std::mutex mtx; LOG_TRACE << "connect!!!" << _max_connection_num << " num=" << _connection_num.load(); @@ -664,7 +664,7 @@ DrogonWebServer::DrogonWebServer() : //pluginsManagerPtr_(new PluginsManager), //uploadPath_(rootPath_ + "uploads") { - _loop = new trantor::EventLoop(); + _loop = new EventLoop(); //_listener_manager = new ListenerManager(); _upload_path = _root_path + "uploads"; diff --git a/web_backends/drogon/drogon_web_server.h b/web_backends/drogon/drogon_web_server.h index 078763c..ae5ccb4 100644 --- a/web_backends/drogon/drogon_web_server.h +++ b/web_backends/drogon/drogon_web_server.h @@ -56,7 +56,7 @@ public: const std::string &get_upload_path() const; - const std::shared_ptr &get_resolver() const; + const std::shared_ptr &get_resolver() const; void set_upload_path(const std::string &uploadPath); void set_file_types(const std::vector &types); @@ -65,7 +65,7 @@ public: void set_max_connection_num_per_ip(size_t maxConnectionsPerIP); void set_log_path(const std::string &logPath, const std::string &logfileBaseName, size_t logfileSize); - void set_log_level(trantor::Logger::LogLevel level); + void set_log_level(Logger::LogLevel level); void enable_sendfile(bool sendFile); void enable_gzip(bool useGzip); bool is_gzip_enabled() const; @@ -110,8 +110,8 @@ public: const std::pair &get_float_precision_in_json() const; - trantor::EventLoop *get_loop() const; - trantor::EventLoop *get_io_loop(size_t id) const; + EventLoop *get_loop() const; + EventLoop *get_io_loop(size_t id) const; void set_server_header_field(const std::string &server); @@ -123,7 +123,7 @@ public: const std::string &get_server_header_string() const; - std::vector get_listeners() const; + std::vector get_listeners() const; bool use_sendfile() const; @@ -137,7 +137,7 @@ public: void on_async_request(const HttpRequestImplPtr &req, std::function &&callback); void on_new_websock_request(const HttpRequestImplPtr &req, std::function &&callback, const WebSocketConnectionImplPtr &wsConnPtr); - void on_connection(const trantor::TcpConnectionPtr &conn); + void on_connection(const TcpConnectionPtr &conn); void find_session_for_request(const HttpRequestImplPtr &req); @@ -197,10 +197,10 @@ protected: bool _enable_date_header{ true }; bool _reuse_port{ false }; - trantor::EventLoop *_loop; + EventLoop *_loop; std::vector > _beginning_advices; - std::vector > _new_connection_advices; + std::vector > _new_connection_advices; std::vector > _sync_advices; std::vector > _pre_sending_advices; }; diff --git a/web_backends/drogon/trantor/utils/NonCopyable.h b/web_backends/drogon/trantor/utils/NonCopyable.h index 5c0af62..4483f22 100644 --- a/web_backends/drogon/trantor/utils/NonCopyable.h +++ b/web_backends/drogon/trantor/utils/NonCopyable.h @@ -16,8 +16,6 @@ #include -namespace trantor -{ /** * @brief This class represents a non-copyable object. * @@ -37,5 +35,3 @@ class TRANTOR_EXPORT NonCopyable NonCopyable(NonCopyable &&) noexcept(true) = default; NonCopyable &operator=(NonCopyable &&) noexcept(true) = default; }; - -} // namespace trantor