Server API rework.

This commit is contained in:
Chunting Gu
2019-06-26 17:34:39 +08:00
parent a65294aeec
commit a3cab444dc
20 changed files with 341 additions and 384 deletions
+24 -18
View File
@@ -1,6 +1,7 @@
#ifndef WEBCC_SERVER_H_
#define WEBCC_SERVER_H_
#include <regex>
#include <string>
#include "boost/asio/io_context.hpp"
@@ -10,33 +11,41 @@
#include "webcc/connection.h"
#include "webcc/connection_pool.h"
#include "webcc/request_handler.h"
#include "webcc/service.h"
#include "webcc/view.h"
namespace webcc {
// HTTP server accepts TCP connections from TCP clients.
// NOTE: Only support IPv4.
class Server {
public:
Server(std::uint16_t port, std::size_t workers,
const std::string& doc_root = "");
Server(std::uint16_t port, std::size_t workers, const Path& doc_root = {});
virtual ~Server() = default;
Server(const Server&) = delete;
Server& operator=(const Server&) = delete;
// Bind a service to the given URL path.
// The URL should start with "/" and it will be treated as a regular
// expression if |is_regex| is true.
// Examples:
// - "/instances"
// - "/instances/(\\d+)"
// Binding to the same URL multiple times is allowed, but only the last one
// takes effect.
bool Bind(ServicePtr service, const std::string& url, bool is_regex);
// Route a URL to a view.
// The URL should start with "/". E.g., "/instances".
bool Route(const std::string& url, ViewPtr view, const Strings& methods) {
return request_handler_.Route(url, view, methods);
}
// Run the server's io_service loop.
bool Route(const std::string& url, ViewPtr view) {
return Route(url, view, { methods::kGet });
}
// Route a regular expression URL to a view.
// The URL should start with "/" and be a regular expression.
// E.g., "/instances/(\\d+)".
bool Route(const RegexUrl& regex_url, ViewPtr view, const Strings& methods) {
return request_handler_.Route(regex_url, view, methods);
}
bool Route(const RegexUrl& regex_url, ViewPtr view) {
return request_handler_.Route(regex_url, view, { methods::kGet });
}
// Run the loop.
void Run();
private:
@@ -49,9 +58,6 @@ private:
// Wait for a request to stop the server.
void DoAwaitStop();
// Get the handler for incoming requests.
//virtual RequestHandler* GetRequestHandler();
// The io_context used to perform asynchronous operations.
boost::asio::io_context io_context_;