webcxx/include/webcxx/App.h
2022-11-03 21:58:25 +01:00

76 lines
1.8 KiB
C++

#pragma once
#include <functional>
#include <map>
#include <memory>
#include <netinet/in.h>
#include <string>
#include <thread>
namespace webcxx {
class Response;
class Request;
class ErrorWatcher;
class App {
public:
static std::shared_ptr<App> create();
int run(int port);
void terminate();
static std::shared_ptr<App> current_app();
void on(int methods, std::string path,
std::function<Response(Request &)> action);
void on_error(int error, std::function<Response(void)> action);
void set_static_resource_path(const std::string& path);
void set_favicon(const std::string& favicon_path);
private:
App() = default;
int socket_init(int);
int main_loop();
bool m_is_running;
int m_socket_fd;
static std::shared_ptr<App> s_instance;
void connection_thread();
std::string static_resource_path = "/static";
int m_current_connection_fd;
sockaddr_in m_addr;
int handle_request(Request& req, int fd);
std::string get_client_addr();
std::vector<std::shared_ptr<std::thread>> m_threads;
struct Action {
std::function<Response(Request &)> get_action;
std::function<Response(Request &)> post_action;
std::function<Response(Request &)> put_action;
std::function<Response(Request &)> delete_action;
};
std::map<std::string, Action> m_action_map;
std::map<int, std::function<Response(void)>> m_error_action_map;
static void app_terminate(int); // Terminate the current app.
static void app_connection_thread();
friend class ErrorWatcher;
};
Response text(const std::string &content);
Response json(const std::string &content);
Response html(const std::string &content, const std::string& title = "");
Response redirect(const std::string &url, int status_code = 302);
Response error(int status_code = 500);
Response file(const std::string& item_path);
} // namespace webcxx