75 lines
1.8 KiB
C++
75 lines
1.8 KiB
C++
#pragma once
|
|
|
|
#include <istream>
|
|
#include <ostream>
|
|
#include <functional>
|
|
#include <map>
|
|
#include <vector>
|
|
#include <string>
|
|
|
|
|
|
class Request : public std::istream
|
|
{
|
|
public:
|
|
Request(std::istream& stream);
|
|
virtual ~Request();
|
|
|
|
Request(const Request&) = delete;
|
|
Request(Request&&) = delete;
|
|
|
|
std::string url() const;
|
|
std::string method() const;
|
|
const std::string* header(std::string name) const;
|
|
};
|
|
|
|
|
|
class Response : public std::ostream
|
|
{
|
|
public:
|
|
Response(std::ostream& stream);
|
|
virtual ~Response();
|
|
|
|
Response(const Response&) = delete;
|
|
Response(Response&&) = delete;
|
|
|
|
void status(int status);
|
|
|
|
template<typename T, std::enable_if_t<std::is_arithmetic<T>::value, bool> = true>
|
|
void header(std::string name, T value) { header(name, std::to_string(value)); }
|
|
void header(std::string name, std::string value);
|
|
|
|
void send(std::string text);
|
|
void send(const void* data, size_t size);
|
|
void sendFile(std::string filename);
|
|
};
|
|
|
|
|
|
using Next = std::function<void()>;
|
|
class Router
|
|
{
|
|
public:
|
|
using Handler = std::function<void(Request&, Response&, Next)>;
|
|
|
|
Router();
|
|
|
|
void handle(std::iostream& req) { handle(req, req); };
|
|
void handle(std::istream& req, std::ostream& res);
|
|
|
|
void on(std::string url, Handler handler);
|
|
|
|
void on_get(std::string url, Handler handler);
|
|
void on_head(std::string url, Handler handler);
|
|
void on_options(std::string url, Handler handler);
|
|
void on_trace(std::string url, Handler handler);
|
|
void on_put(std::string url, Handler handler);
|
|
void on_delete(std::string url, Handler handler);
|
|
void on_post(std::string url, Handler handler);
|
|
void on_patch(std::string url, Handler handler);
|
|
void on_connect(std::string url, Handler handler);
|
|
|
|
void listen(std::string address, short port);
|
|
void listen(short port);
|
|
|
|
private:
|
|
std::map<std::string, std::vector<Handler>> _handlers;
|
|
}; |