Browse Source

basic http server

master
Thomas Lindner 8 months ago
parent
commit
999d53b113
  1. 2
      .clang-tidy
  2. 4
      CMakeLists.txt
  3. 2
      cmake/GlobalOptions.cmake
  4. 2
      src/CMakeLists.txt
  5. 54
      src/main.cc

2
.clang-tidy

@ -1,5 +1,5 @@
---
Checks: 'clang-diagnostic-*,clang-analyzer-*,*,-llvmlibc-implementation-in-namespace,-modernize-use-trailing-return-type'
Checks: 'clang-diagnostic-*,clang-analyzer-*,*,-llvmlibc-*,-modernize-use-trailing-return-type'
WarningsAsErrors: ''
HeaderFilterRegex: ''
AnalyzeTemporaryDtors: false

4
CMakeLists.txt

@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.20)
project(basiccmake LANGUAGES CXX)
project(board LANGUAGES CXX)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
include(GlobalOptions)
@ -7,7 +7,7 @@ include(GNUInstallDirs)
include(Format)
# keep PUBLIC dependencies in sync with cmake/config.cmake.in
#find_package(foo REQUIRED)
find_package(Boost REQUIRED)
add_subdirectory(src)

2
cmake/GlobalOptions.cmake

@ -1,3 +1,3 @@
add_compile_options(-Wall -Werror -Wno-unknown-warning-option)
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_CLANG_TIDY clang-tidy --config=)
#set(CMAKE_CXX_CLANG_TIDY clang-tidy --config=)

2
src/CMakeLists.txt

@ -1,7 +1,7 @@
add_executable(${PROJECT_NAME} main.cc)
target_link_libraries(${PROJECT_NAME}
PRIVATE
)
Boost::boost)
target_include_directories(${PROJECT_NAME}
PUBLIC
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>

54
src/main.cc

@ -1,3 +1,57 @@
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <iostream>
namespace asio = boost::asio;
namespace beast = boost::beast;
namespace http = beast::http;
using boost::asio::ip::tcp;
class Server {
using tcp_acceptor = asio::use_awaitable_t<>::as_default_on_t<tcp::acceptor>;
using tcp_socket = asio::use_awaitable_t<>::as_default_on_t<tcp::socket>;
asio::awaitable<void> HandleRequest(tcp_socket socket) {
bool close;
beast::flat_buffer buffer;
do {
http::request<http::empty_body> req;
co_await http::async_read(socket, buffer, req);
http::response<http::string_body> res{http::status::ok, req.version()};
res.keep_alive(req.keep_alive());
res.body() = "foo\n";
co_await http::async_write(socket, res);
close = res.need_eof();
} while (!close);
socket.shutdown(tcp::socket::shutdown_send);
co_return;
}
asio::awaitable<void> Listen() {
auto executor = co_await asio::this_coro::executor;
tcp_acceptor acceptor{executor, {tcp::v4(), 8080}};
while (true) {
tcp_socket socket = co_await acceptor.async_accept();
co_spawn(executor, HandleRequest(std::move(socket)), asio::detached);
}
}
public:
Server(asio::io_context *context) {
co_spawn(*context, Listen(), asio::detached);
}
};
int main() {
asio::io_context context;
asio::signal_set signals{context, SIGINT, SIGTERM};
signals.async_wait([&](auto, auto) { context.stop(); });
Server server{&context};
context.run();
return 0;
}

Loading…
Cancel
Save