summaryrefslogtreecommitdiff
path: root/bot/include/http_webhook_server.hpp
blob: a42829f92ddf87bc013ea9243444b9cb9914ef17 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#pragma once

#include <sys/epoll.h>
#include <netinet/in.h>
#include <functional>
#include <string>
#include <unordered_map>
#include <system_error>
#include <sstream>

class HttpWebhookServer {
public:
    struct HttpRequest {
        std::string method;
        std::string path;
        std::unordered_map<std::string, std::string> headers;
        std::string body;
    };

    struct HttpResponse {
        int status_code = 200;
        std::unordered_map<std::string, std::string> headers;
        std::string body;
    };

    using Handler = std::function<HttpResponse(const HttpRequest&)>;

    HttpWebhookServer(uint16_t port, Handler handler);
    ~HttpWebhookServer();

    void start();
    void stop();

private:
    struct ClientContext {
        std::string input_buffer;
        std::string output_buffer;
        size_t bytes_written = 0;
    };

    void setupSocket();
    void setupEpoll();
    void handleEvent(struct epoll_event* event);
    void handleClient(int fd);
    void closeClient(int fd);
    void parseHttpRequest(ClientContext& ctx, HttpRequest& req);
    void buildHttpResponse(const HttpResponse& res, std::string& output);

    int server_fd = -1;
    int epoll_fd = -1;
    bool running = false;
    uint16_t port;
    Handler request_handler;
    std::unordered_map<int, ClientContext> clients;
};