Skip to content

Commit

Permalink
http handler
Browse files Browse the repository at this point in the history
  • Loading branch information
uchenily committed Jun 4, 2024
1 parent a9c0d9d commit e6eca11
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 7 deletions.
7 changes: 6 additions & 1 deletion examples/http_server.cpp
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
#include "uvio/debug.hpp"
#include "uvio/net/http.hpp"
#include "uvio/net/http/http_protocol.hpp"

using namespace uvio::net;
auto main() -> int {
http::HttpServer server{"127.0.0.1", 8000};
http::HttpServer server{"0.0.0.0", 8000};
server.set_handler("/",
[](http::HttpRequest &req, http::HttpResponse &resp) {
resp.body = "hello";
});
server.run();
}
3 changes: 2 additions & 1 deletion uvio/net/http/http_frame.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,8 @@ class HttpFramed {
[[REMEMBER_CO_AWAIT]]
auto read_request() -> Task<Result<HttpRequest>> {
auto result = co_await codec_.Decode(buffered_reader_);
co_return HttpRequest{.body = result.value()};
// FIXME: Decode() -> HttpRequest?
co_return HttpRequest{.url = "/", .body = result.value()};
}

private:
Expand Down
34 changes: 29 additions & 5 deletions uvio/net/http/http_server.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,28 @@

#include "uvio/core.hpp"
#include "uvio/debug.hpp"
#include "uvio/net/http/http_frame.hpp"
#include "uvio/net/http/http_protocol.hpp"
#include "uvio/net/tcp_listener.hpp"

#include <unordered_map>

namespace uvio::net::http {

class HttpServer {
using HandlerFunc
= std::function<void(HttpRequest &req, HttpResponse &resp)>;

public:
HttpServer(std::string_view host, int port)
: host_{host}
, port_{port} {}

public:
auto set_handler(std::string_view url, HandlerFunc &&func) {
map_handles_[url] = std::move(func);
}

auto run() {
block_on([this]() -> Task<> {
auto listener = TcpListener();
Expand All @@ -36,12 +47,23 @@ class HttpServer {
}

auto request = std::move(req.value());
LOG_DEBUG("request.body: {}", request.body);
LOG_DEBUG("request url: {} body: {}", request.url, request.body);

HttpResponse resp{
.http_code = 200,
.body = "<h1>Hello</h1>",
};
HttpResponse resp;
if (auto it = map_handles_.find(request.url);
it != map_handles_.end()) {
it->second(request, resp);
resp.http_code = 200;
} else {
// TODO(x)
resp.body = "Page not found";
resp.http_code = 404;
}

// HttpResponse resp{
// .http_code = 200,
// .body = "<h1>Hello</h1>",
// };

if (auto res = co_await http_framed.write_response(resp); !res) {
console.error("{}", res.error().message());
Expand All @@ -53,6 +75,8 @@ class HttpServer {
std::string host_;
int port_;
TcpStream stream_{nullptr};

std::unordered_map<std::string_view, HandlerFunc> map_handles_;
};

} // namespace uvio::net::http

0 comments on commit e6eca11

Please sign in to comment.