Commit 857fd82b authored by octal's avatar octal

Implemented a listenAndServe function and fixed a bug in Address parsing

parent d698fbe4
......@@ -80,6 +80,22 @@ private:
Net::Tcp::Listener listener;
};
template<typename Handler>
void listenAndServe(Address addr)
{
auto options = Endpoint::options().threads(1);
listenAndServe<Handler>(addr, options);
}
template<typename Handler>
void listenAndServe(Address addr, const Endpoint::Options& options)
{
Endpoint endpoint(addr);
endpoint.init(options);
endpoint.setHandler(make_handler<Handler>());
endpoint.serve();
}
} // namespace Http
......
......@@ -9,6 +9,7 @@
#include <sys/socket.h>
#include <cstring>
#include <stdexcept>
#include <limits>
#ifndef _KERNEL_FASTOPEN
#define _KERNEL_FASTOPEN
......@@ -30,6 +31,10 @@ public:
bool isReserved() const;
bool isUsed() const;
static constexpr uint16_t max() {
return std::numeric_limits<uint16_t>::max();
}
private:
uint16_t port;
};
......@@ -53,6 +58,7 @@ public:
Address();
Address(std::string host, Port port);
Address(std::string addr);
Address(const char* addr);
Address(Ipv4 ip, Port port);
Address(const Address& other) = default;
......@@ -67,6 +73,7 @@ public:
Port port() const;
private:
void init(std::string addr);
std::string host_;
Port port_;
};
......
......@@ -11,6 +11,7 @@
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
using namespace std;
......@@ -66,21 +67,12 @@ Address::Address(std::string host, Port port)
Address::Address(std::string addr)
{
auto pos = addr.find(':');
if (pos == std::string::npos)
throw std::invalid_argument("Invalid address");
std::string host = addr.substr(0, pos);
char *end;
const std::string portPart = addr.substr(pos + 1);
long port = strtol(portPart.c_str(), &end, 10);
if (*end != 0 || port > std::numeric_limits<Port>::max())
throw std::invalid_argument("Invalid port");
init(std::move(addr));
}
host_ = std::move(host);
port_ = port;
Address::Address(const char* addr)
{
init(std::string(addr));
}
Address::Address(Ipv4 ip, Port port)
......@@ -98,14 +90,35 @@ Address::fromUnix(struct sockaddr* addr) {
return Address(std::move(host), port);
}
std::string Address::host() const {
std::string
Address::host() const {
return host_;
}
Port Address::port() const {
Port
Address::port() const {
return port_;
}
void
Address::init(std::string addr) {
auto pos = addr.find(':');
if (pos == std::string::npos)
throw std::invalid_argument("Invalid address");
std::string host = addr.substr(0, pos);
char *end;
const std::string portPart = addr.substr(pos + 1);
long port = strtol(portPart.c_str(), &end, 10);
if (*end != 0 || port > Port::max())
throw std::invalid_argument("Invalid port");
host_ = std::move(host);
port_ = port;
}
Error::Error(const char* message)
: std::runtime_error(message)
{ }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment