Compare commits

...

10 Commits

Author SHA1 Message Date
Антон ed3bcc6f4a add config.json 2024-02-21 05:57:28 +03:00
Антон 556c0548a9 add config.json 2024-02-07 19:00:49 +03:00
Антон 2f729981fa add config.json 2024-01-20 18:47:02 +03:00
Антон 4230d9ec24 extract route 2024-01-20 12:46:22 +03:00
Антон 42382261a7 Refactoring 2024-01-20 12:24:00 +03:00
Антон 3d1ded8573 Change codeStyle 2024-01-15 19:31:57 +03:00
Антон 2c8518b092 Change codeStyle 2023-11-04 02:05:40 +03:00
Sithas777 0ff54f68f2 Запущенный асинхронный сервер 2023-09-14 21:39:36 +03:00
Sithas777 a80508d3a8 Вторая часть - база для сессии
Для обработки запроса нужно вызвать функцию request_handler_
2023-09-13 18:51:20 +03:00
Sithas777 d2fc912071 Вторая часть - база для сессии
Для обработки запроса нужно вызвать функцию request_handler_
2023-09-13 18:41:18 +03:00
8 changed files with 161 additions and 136 deletions

View File

@ -5,29 +5,31 @@ set(CMAKE_CXX_STANDARD 20)
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)
set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "/home/oem/Libs/boost/1.82.0/include")
set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "/home/oem/Libs/boost/1.82.0/lib")
set(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "C:/Users/Public/Libraries/boost_1_84_0")
set(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} "C:/Users/Public/Libraries/boost_1_84_0/stage/lib")
#include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
# conan_basic_setup()
find_package(Boost 1.78.0 REQUIRED)
if(Boost_FOUND)
if (Boost_FOUND)
include_directories(${Boost_INCLUDE_DIRS})
endif()
endif ()
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
configure_file(config.json ${CMAKE_BUILD_RPATH} config.json COPYONLY)
add_executable(hello_async
main.cpp
src/http_server.cpp
src/http_server.h
src/session.h
src/session.cpp
src/session_base.h
src/session_base.cpp
src/listener.h
src/listener.cpp
src/sdk.h)
main.cpp
src/http_server.cpp
src/http_server.h
src/session.h
src/session.cpp
src/session_base.h
src/session_base.cpp
src/listener.h
src/listener.cpp
src/sdk.h)
target_link_libraries(hello_async PRIVATE Threads::Threads)

View File

@ -1,92 +0,0 @@
# CPP_Backend_task
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.com/Paumpeero/cpp_backend_task.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.com/Paumpeero/cpp_backend_task/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

10
config.json Normal file
View File

@ -0,0 +1,10 @@
{
"maps": {
"map1": {
"a": 123
},
"map2": {
"b": 456
}
}
}

View File

@ -22,18 +22,19 @@ using StringRequest = http::request<http::string_body>;
// Ответ, тело которого представлено в виде строки
using StringResponse = http::response<http::string_body>;
struct ContentType
struct content_type
{
ContentType() = delete;
constexpr static std::string_view
TEXT_HTML = "text/html"sv;
// При необходимости внутрь ContentType можно добавить и другие типы контента
content_type() = delete;
constexpr static std::string_view k_TextHTML = "text/html"sv;
// При необходимости внутрь content_type можно добавить и другие типы контента
};
// Создаёт StringResponse с заданными параметрами
StringResponse MakeStringResponse(http::status status, std::string_view body, unsigned http_version,
StringResponse MakeStringResponse(http::status status,
std::string_view body,
unsigned http_version,
bool keep_alive,
std::string_view content_type = ContentType::TEXT_HTML)
std::string_view content_type = content_type::k_TextHTML)
{
StringResponse response(status, http_version);
response.set(http::field::content_type, content_type);
@ -45,8 +46,12 @@ StringResponse MakeStringResponse(http::status status, std::string_view body, un
StringResponse HandleRequest(StringRequest&& req)
{
// Подставьте сюда код из синхронной версии HTTP-сервера
return MakeStringResponse(http::status::ok, "OK"sv, req.version(), req.keep_alive());
auto route = req.target();
return MakeStringResponse(http::status::ok,
"Hello, World!"sv,
req.version(),
req.keep_alive());
}
// Запускает функцию fn на n потоках, включая текущий
@ -75,11 +80,13 @@ int main()
// Подписываемся на сигналы и при их получении завершаем работу сервера
net::signal_set signals(ioc, SIGINT, SIGTERM);
signals.async_wait([&ioc](const sys::error_code& ec, [[maybe_unused]] int signal_number)
signals.async_wait([&ioc](const sys::error_code& ec,
[[maybe_unused]] int signal_number)
{
if (!ec)
{
cout << "Signal "sv << signal_number << " received"sv << endl;
cout << "Signal "sv << signal_number << " received"sv
<< endl;
ioc.stop();
}
});
@ -88,7 +95,7 @@ int main()
constexpr net::ip::port_type port = 8080;
http_server::ServeHttp(ioc, {address, port}, [](auto&& req, auto&& sender)
{
// sender(HandleRequest(std::forward<decltype(req)>(req)));
sender(HandleRequest(std::forward<decltype(req)>(req)));
});
net::steady_timer t {ioc, 30s};
@ -98,7 +105,6 @@ int main()
cout << "Timer expired"sv << endl;
});
// Эта надпись сообщает тестам о том, что сервер запущен и готов обрабатывать запросы
std::cout << "Server has started..."sv << std::endl;
RunWorkers(num_threads, [&ioc]

View File

@ -14,8 +14,14 @@
namespace http_server
{
template<typename RequestHandler>
void ServeHttp(net::io_context& ioc, const tcp::endpoint& endpoint, RequestHandler&& handler)
void ServeHttp(net::io_context& ioc,
const tcp::endpoint& endpoint,
RequestHandler&& handler)
{
// Напишите недостающий код, используя информацию из урока
using MyListener = Listener<std::decay_t < RequestHandler>>;
std::make_shared<MyListener>(ioc,
endpoint,
std::forward<RequestHandler>(handler))->Run();
}
}

View File

@ -10,26 +10,42 @@
#include "session_base.h"
namespace http_server {
namespace http_server
{
namespace net = boost::asio;
using tcp = net::ip::tcp;
namespace beast = boost::beast;
namespace http = beast::http;
template <typename RequestHandler>
class Session : public SessionBase, public std::enable_shared_from_this<Session<RequestHandler>> {
template<typename RequestHandler>
class Session
: public SessionBase,
public std::enable_shared_from_this<Session<RequestHandler>>
{
RequestHandler request_handler_;
public:
template<class Handler>
Session(tcp::socket&& socket, Handler&& request_handler)
: SessionBase(std::move(socket)), request_handler_(request_handler)
{}
: SessionBase(std::move(socket)), request_handler_(request_handler) {}
std::shared_ptr<SessionBase> GetSharedThis() override
{
return this->shared_from_this();
}
private:
void HandleRequest(HttpRequest&& request) override
{
// Захватываем умный указатель на текущий объект Session в лямбде,
// чтобы продлить время жизни сессии до вызова лямбды.
// Используется generic-лямбда функция, способная принять response произвольного типа
request_handler_(std::move(request),
[self = this->shared_from_this()](auto&& response)
{
self->Write(std::move(response));
});
}
};
} // namespace http_server

View File

@ -6,20 +6,68 @@
namespace http_server
{
void ReportError(beast::error_code ec, std::string_view what) {
void ReportError(beast::error_code ec, std::string_view what)
{
std::cerr << what << ": "sv << ec.message() << std::endl;
}
SessionBase::SessionBase(tcp::socket&& socket)
: stream_(std::move(socket))
: stream_(std::move(socket))
{
}
void SessionBase::Run()
{
net::dispatch(stream_.get_executor(),
beast::bind_front_handler(&SessionBase::Read,
GetSharedThis()));
}
void SessionBase::Read()
{
using namespace std::literals;
request_ = {};
stream_.expires_after(30s);
http::async_read(stream_, buffer_, request_,
beast::bind_front_handler(&SessionBase::OnRead,
GetSharedThis()));
}
void SessionBase::OnRead(beast::error_code ec, size_t bytes_read)
{
if (ec == http::error::end_of_stream)
{
return Close();
}
if (ec)
{
return ReportError(ec, "read"sv);
}
HandleRequest(std::move(request_));
}
void SessionBase::Close()
{
beast::error_code ec;
stream_.socket().shutdown(tcp::socket::shutdown_send, ec);
}
void SessionBase::OnWrite(bool close,
boost::beast::error_code ec,
std::size_t bytes_written)
{
if (ec)
{
return ReportError(ec, "write"sv);
}
if (close)
{
// Семантика ответа требует закрыть соединение
return Close();
}
// Считываем следующий запрос
Read();
}
} // namespace http_server

View File

@ -11,8 +11,8 @@
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
namespace http_server {
namespace http_server
{
namespace net = boost::asio;
using tcp = net::ip::tcp;
namespace beast = boost::beast;
@ -22,11 +22,12 @@ using namespace std::literals;
void ReportError(beast::error_code ec, std::string_view what);
class SessionBase {
class SessionBase
{
protected:
using HttpRequest = http::request<http::string_body>;
~SessionBase() = default;
virtual ~SessionBase() = default;
public:
SessionBase(const SessionBase&) = delete;
@ -40,9 +41,37 @@ class SessionBase {
protected:
explicit SessionBase(tcp::socket&& socket);
template<typename Body, typename Fields>
void Write(http::response<Body, Fields>&& response)
{
// Запись выполняется асинхронно, поэтому response перемещаем в область кучи
auto safe_response = std::make_shared < http::response
< Body, Fields>>(std::move(response));
auto self = GetSharedThis();
http::async_write(stream_, *safe_response,
[safe_response, self](beast::error_code ec,
std::size_t bytes_written)
{
self->OnWrite(safe_response->need_eof(),
ec,
bytes_written);
});
}
private:
beast::tcp_stream stream_;
beast::tcp_stream stream_;
beast::flat_buffer buffer_;
HttpRequest request_;
HttpRequest request_;
void OnRead(beast::error_code ec, [[maybe_unused]] size_t bytes_read);
void Close();
virtual void HandleRequest(HttpRequest&& request) = 0;
void OnWrite(bool close,
beast::error_code ec,
[[maybe_unused]] std::size_t bytes_written);
};
} // namespace http_server