basic http server

This commit is contained in:
Thomas Lindner 2021-11-22 00:37:36 +01:00
parent c60811620a
commit 999d53b113
5 changed files with 59 additions and 5 deletions

View file

@ -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

View file

@ -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)

View file

@ -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=)

View file

@ -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>

View file

@ -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;
}