Line data Source code
1 : #ifndef THINGER_HTTP_SERVER_STANDALONE_HPP
2 : #define THINGER_HTTP_SERVER_STANDALONE_HPP
3 :
4 : #include "server_base.hpp"
5 : #include <boost/asio/io_context.hpp>
6 : #include <boost/asio/executor_work_guard.hpp>
7 :
8 : namespace thinger::http {
9 :
10 : /**
11 : * Standalone HTTP server that uses its own io_context.
12 : * Perfect for simple applications that don't need the full worker infrastructure.
13 : * Single-threaded server that runs in the thread that calls wait(): every listener accepts and
14 : * serves on it.
15 : */
16 : class server : public server_base {
17 : private:
18 : // Own io_context for handling async operations
19 : boost::asio::io_context io_context_;
20 :
21 : // Work guard to keep io_context running
22 : using work_guard_type = boost::asio::executor_work_guard<boost::asio::io_context::executor_type>;
23 : std::unique_ptr<work_guard_type> work_guard_;
24 :
25 : std::atomic<bool> running_{false};
26 : // A thread runs the io_context (see wait())
27 : std::atomic<bool> serving_{false};
28 :
29 : // Stop listening and the io_context, releasing wait()
30 : void stop_running();
31 :
32 : protected:
33 : // A listener accepting and serving on our io_context
34 : std::unique_ptr<asio::listener> create_listener(asio::listener_options options) override;
35 : // The first listener opened: the io_context may run (see wait())
36 : void listening() override;
37 :
38 : boost::asio::io_context* shutdown_context() override;
39 : bool in_server_thread() override;
40 :
41 : public:
42 : // Constructor - single threaded server
43 : server();
44 : ~server() override;
45 :
46 : // Run the io_context in the calling thread until the server stops: at once if it does not
47 : // listen
48 : void wait() override;
49 :
50 : // Stop the server
51 : void stop() override;
52 :
53 : // Get direct access to io_context for advanced use cases
54 21 : boost::asio::io_context& get_io_context() {
55 21 : return io_context_;
56 : }
57 : };
58 :
59 : } // namespace thinger::http
60 :
61 : #endif // THINGER_HTTP_SERVER_STANDALONE_HPP
|