Rename RegisterService to Bind and add is_regex parameter; indent public/protected/private by one space; refine rest example.

This commit is contained in:
Adam Gu
2018-05-22 15:45:38 +08:00
parent 1bab2da8f4
commit cdc61b4bf2
36 changed files with 182 additions and 235 deletions
+2 -2
View File
@@ -91,8 +91,8 @@ Parameter::Parameter(const std::string& key, bool value)
}
Parameter::Parameter(Parameter&& rhs)
: key_(std::move(rhs.key_))
, value_(std::move(rhs.value_)) {
: key_(std::move(rhs.key_)),
value_(std::move(rhs.value_)) {
}
Parameter& Parameter::operator=(Parameter&& rhs) {
+2 -2
View File
@@ -113,7 +113,7 @@ const char* GetErrorMessage(Error error);
// Key-value parameter.
class Parameter {
public:
public:
Parameter() = default;
Parameter(const Parameter&) = default;
Parameter& operator=(const Parameter&) = default;
@@ -150,7 +150,7 @@ public:
// Return "key=value" string.
std::string ToString() const;
private:
private:
std::string key_;
std::string value_;
};
+1 -2
View File
@@ -36,8 +36,7 @@ HttpClient::HttpClient()
CheckDeadline();
}
Error HttpClient::MakeRequest(const HttpRequest& request,
HttpResponse* response) {
Error HttpClient::Request(const HttpRequest& request, HttpResponse* response) {
assert(response != NULL);
Error error = kNoError;
+5 -8
View File
@@ -17,23 +17,19 @@ class HttpRequest;
class HttpResponse;
class HttpClient {
public:
public:
HttpClient();
~HttpClient() = default;
HttpClient(const HttpClient&) = delete;
HttpClient& operator=(const HttpClient&) = delete;
void set_timeout_seconds(int timeout_seconds) {
timeout_seconds_ = timeout_seconds;
}
// Make a HTTP request.
// Connect to the server, send the request, wait until the response is
// received.
Error MakeRequest(const HttpRequest& request, HttpResponse* response);
Error Request(const HttpRequest& request, HttpResponse* response);
private:
private:
Error Connect(const HttpRequest& request);
Error SendReqeust(const HttpRequest& request);
@@ -42,7 +38,6 @@ private:
void CheckDeadline();
private:
boost::asio::io_context io_context_;
boost::asio::ip::tcp::socket socket_;
@@ -57,6 +52,8 @@ private:
// Timer for the timeout control.
boost::asio::deadline_timer deadline_timer_;
DISALLOW_COPY_AND_ASSIGN(HttpClient);
};
} // namespace webcc
+3 -4
View File
@@ -9,14 +9,14 @@
namespace webcc {
class HttpHeader {
public:
public:
std::string name;
std::string value;
};
// Base class for HTTP request and response messages.
class HttpMessage {
public:
public:
virtual ~HttpMessage() = default;
const std::string& start_line() const {
@@ -51,13 +51,12 @@ public:
SetContentLength(content_.size());
}
private:
protected:
void SetContentLength(std::size_t content_length) {
content_length_ = content_length;
SetHeader(kContentLength, std::to_string(content_length));
}
protected:
// Start line with trailing "\r\n".
std::string start_line_;
+2 -2
View File
@@ -17,7 +17,7 @@ class HttpResponse;
// The common handler for all incoming requests.
class HttpRequestHandler {
public:
public:
HttpRequestHandler() = default;
virtual ~HttpRequestHandler() = default;
@@ -30,7 +30,7 @@ public:
// Close pending sessions and stop worker threads.
void Stop();
private:
private:
void WorkerRoutine();
// Called by the worker routine.
+2 -2
View File
@@ -8,12 +8,12 @@ namespace webcc {
class HttpRequest;
class HttpRequestParser : public HttpParser {
public:
public:
explicit HttpRequestParser(HttpRequest* request);
~HttpRequestParser() override = default;
private:
private:
Error ParseStartLine(const std::string& line) override;
HttpRequest* request_;
+2 -2
View File
@@ -14,7 +14,7 @@ class HttpResponse;
std::ostream& operator<<(std::ostream& os, const HttpResponse& response);
class HttpResponse : public HttpMessage {
public:
public:
HttpResponse() = default;
~HttpResponse() override = default;
@@ -37,7 +37,7 @@ public:
// Get a fault response when HTTP status is not OK.
static HttpResponse Fault(HttpStatus::Enum status);
private:
private:
friend std::ostream& operator<<(std::ostream& os,
const HttpResponse& response);
+2 -3
View File
@@ -8,16 +8,15 @@ namespace webcc {
class HttpResponse;
class HttpResponseParser : public HttpParser {
public:
public:
explicit HttpResponseParser(HttpResponse* response);
~HttpResponseParser() override = default;
private:
private:
// Parse HTTP start line; E.g., "HTTP/1.1 200 OK".
Error ParseStartLine(const std::string& line) override;
private:
// The result response message.
HttpResponse* response_;
};
+5 -6
View File
@@ -10,6 +10,7 @@
#include "boost/scoped_ptr.hpp"
#include "boost/thread/thread.hpp"
#include "webcc/globals.h"
#include "webcc/http_session.h"
namespace webcc {
@@ -19,10 +20,7 @@ class HttpRequestHandler;
// HTTP server accepts TCP connections from TCP clients.
// NOTE: Only support IPv4.
class HttpServer {
public:
HttpServer(const HttpServer&) = delete;
HttpServer& operator=(const HttpServer&) = delete;
public:
HttpServer(unsigned short port, std::size_t workers);
virtual ~HttpServer() = default;
@@ -30,7 +28,7 @@ public:
// Run the server's io_service loop.
void Run();
private:
private:
// Initiate an asynchronous accept operation.
void AsyncAccept();
@@ -40,7 +38,6 @@ private:
// Get the handler for incoming requests.
virtual HttpRequestHandler* GetRequestHandler() = 0;
private:
// The number of worker threads.
std::size_t workers_;
@@ -52,6 +49,8 @@ private:
// Acceptor used to listen for incoming connections.
boost::scoped_ptr<boost::asio::ip::tcp::acceptor> acceptor_;
DISALLOW_COPY_AND_ASSIGN(HttpServer);
};
} // namespace webcc
+2 -3
View File
@@ -16,7 +16,7 @@ namespace webcc {
class HttpRequestHandler;
class HttpSession : public std::enable_shared_from_this<HttpSession> {
public:
public:
HttpSession(const HttpSession&) = delete;
HttpSession& operator=(const HttpSession&) = delete;
@@ -41,14 +41,13 @@ public:
// Send response to client with the given status.
void SendResponse(HttpStatus::Enum status);
private:
private:
void AsyncRead();
void ReadHandler(boost::system::error_code ec, std::size_t length);
void AsyncWrite();
void WriteHandler(boost::system::error_code ec, std::size_t length);
private:
// Socket for the connection.
boost::asio::ip::tcp::socket socket_;
+2 -2
View File
@@ -14,7 +14,7 @@ namespace webcc {
template <typename T>
class Queue {
public:
public:
Queue() = default;
Queue(const Queue&) = delete;
@@ -51,7 +51,7 @@ public:
not_empty_cv_.notify_one();
}
private:
private:
std::list<T> message_list_;
boost::mutex mutex_;
boost::condition_variable not_empty_cv_;
+1 -1
View File
@@ -23,7 +23,7 @@ bool RestClient::Request(const std::string& method,
request.Build();
HttpClient http_client;
Error error = http_client.MakeRequest(request, response);
Error error = http_client.Request(request, response);
return error == kNoError;
}
+2 -2
View File
@@ -10,7 +10,7 @@ namespace webcc {
class HttpResponse;
class RestClient {
public:
public:
RestClient(const std::string& host, const std::string& port)
: host_(host), port_(port) {
}
@@ -41,7 +41,7 @@ public:
return Request(kHttpDelete, url, "", response);
}
private:
private:
bool Request(const std::string& method,
const std::string& url,
const std::string& content,
+4 -3
View File
@@ -5,9 +5,10 @@
namespace webcc {
bool RestRequestHandler::RegisterService(RestServicePtr service,
const std::string& url) {
return service_manager_.AddService(service, url);
bool RestRequestHandler::Bind(RestServicePtr service,
const std::string& url,
bool is_regex) {
return service_manager_.AddService(service, url, is_regex);
}
void RestRequestHandler::HandleSession(HttpSessionPtr session) {
+3 -7
View File
@@ -9,18 +9,14 @@
namespace webcc {
class RestRequestHandler : public HttpRequestHandler {
public:
public:
~RestRequestHandler() override = default;
// Register a REST service to the given URL path.
// The URL should start with "/" and could be a regular expression or not.
// E.g., "/instances". "/instances/(\\d+)"
bool RegisterService(RestServicePtr service, const std::string& url);
bool Bind(RestServicePtr service, const std::string& url, bool is_regex);
private:
private:
void HandleSession(HttpSessionPtr session) override;
private:
RestServiceManager service_manager_;
};
+12 -10
View File
@@ -10,28 +10,30 @@
namespace webcc {
class RestServer : public HttpServer {
public:
public:
RestServer(unsigned short port, std::size_t workers)
: HttpServer(port, workers) {
}
~RestServer() override = default;
// Register a REST service to the given URL path.
// The URL should start with "/" and could be a regular expression or not.
// E.g., "/instances". "/instances/(\\d+)"
// NOTE: Registering to the same URL multiple times is allowed, but only the
// last one takes effect.
bool RegisterService(RestServicePtr service, const std::string& url) {
return request_handler_.RegisterService(service, url);
// Bind a REST 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(RestServicePtr service, const std::string& url, bool is_regex) {
return request_handler_.Bind(service, url, is_regex);
}
private:
private:
HttpRequestHandler* GetRequestHandler() override {
return &request_handler_;
}
private:
RestRequestHandler request_handler_;
};
+1 -1
View File
@@ -23,7 +23,7 @@ class UrlQuery;
// Base class for your REST service.
class RestService {
public:
public:
virtual ~RestService() {
}
+24 -14
View File
@@ -7,10 +7,16 @@
namespace webcc {
bool RestServiceManager::AddService(RestServicePtr service,
const std::string& url) {
const std::string& url,
bool is_regex) {
assert(service);
ServiceItem item(service, url);
ServiceItem item(service, url, is_regex);
if (!is_regex) {
service_items_.push_back(std::move(item));
return true;
}
std::regex::flag_type flags = std::regex::ECMAScript | std::regex::icase;
@@ -18,15 +24,13 @@ bool RestServiceManager::AddService(RestServicePtr service,
// Compile the regex.
item.url_regex.assign(url, flags);
service_items_.push_back(item);
service_items_.push_back(std::move(item));
return true;
} catch (std::regex_error& e) {
LOG_ERRO("URL is not a valid regular expression: %s", e.what());
return false;
}
return false;
}
RestServicePtr RestServiceManager::GetService(
@@ -36,16 +40,22 @@ RestServicePtr RestServiceManager::GetService(
assert(sub_matches != NULL);
for (ServiceItem& item : service_items_) {
std::smatch match;
if (item.is_regex) {
std::smatch match;
if (std::regex_match(url, match, item.url_regex)) {
// Any sub-matches?
// NOTE: Start from 1 because match[0] is the whole string itself.
for (size_t i = 1; i < match.size(); ++i) {
sub_matches->push_back(match[i].str());
if (std::regex_match(url, match, item.url_regex)) {
// Any sub-matches?
// NOTE: Start from 1 because match[0] is the whole string itself.
for (size_t i = 1; i < match.size(); ++i) {
sub_matches->push_back(match[i].str());
}
return item.service;
}
} else {
if (item.url == url) {
return item.service;
}
return item.service;
}
}
+20 -13
View File
@@ -9,13 +9,15 @@
namespace webcc {
class RestServiceManager {
public:
public:
RestServiceManager() = default;
// Add a service and bind it with the given URL.
// The |url| should start with "/" and could be a regular expression or not.
// E.g., "/instances". "/instances/(\\d+)"
bool AddService(RestServicePtr service, const std::string& url);
// The |url| should start with "/" and will be treated as a regular expression
// if |regex| is true.
// Examples: "/instances", "/instances/(\\d+)".
bool AddService(RestServicePtr service, const std::string& url,
bool is_regex);
// The |sub_matches| is only available when the |url| bound to the
// service is a regular expression and has sub-expressions.
@@ -24,20 +26,22 @@ public:
RestServicePtr GetService(const std::string& url,
std::vector<std::string>* sub_matches);
private:
private:
class ServiceItem {
public:
ServiceItem(RestServicePtr _service, const std::string& _url)
: service(_service), url(_url) {
public:
ServiceItem(RestServicePtr _service, const std::string& _url,
bool _is_regex)
: service(_service), url(_url), is_regex(_is_regex) {
}
ServiceItem(const ServiceItem& rhs) = default;
ServiceItem& operator=(const ServiceItem& rhs) = default;
ServiceItem(const ServiceItem&) = default;
ServiceItem& operator=(const ServiceItem&) = default;
ServiceItem(ServiceItem&& rhs)
: url(std::move(rhs.url)),
url_regex(std::move(rhs.url_regex)),
service(rhs.service) { // No move
: service(rhs.service),
url(std::move(rhs.url)),
is_regex(rhs.is_regex),
url_regex(std::move(rhs.url_regex)) {
}
RestServicePtr service;
@@ -45,6 +49,9 @@ private:
// URL string, e.g., "/instances/(\\d+)".
std::string url;
// If the URL is a regular expression or not.
bool is_regex;
// Compiled regex for URL string.
std::regex url_regex;
};
+1 -1
View File
@@ -53,7 +53,7 @@ Error SoapClient::Call(const std::string& operation,
http_client.set_timeout_seconds(timeout_seconds_);
}
Error error = http_client.MakeRequest(http_request, &http_response);
Error error = http_client.Request(http_request, &http_response);
if (error != kNoError) {
return error;
+2 -3
View File
@@ -13,10 +13,10 @@ namespace webcc {
// Set URL, host, port, etc. in your sub-class before make the call.
//
class SoapClient {
public:
public:
virtual ~SoapClient() = default;
protected:
protected:
SoapClient() = default;
// A generic wrapper to make a call.
@@ -25,7 +25,6 @@ protected:
std::vector<Parameter>&& parameters,
std::string* result);
protected:
// -1 means default timeout (normally 30s) will be used.
int timeout_seconds_ = -1;
+3 -4
View File
@@ -12,7 +12,7 @@ namespace webcc {
// XML namespace name/url pair.
// E.g., { "soap", "http://schemas.xmlsoap.org/soap/envelope/" }
class SoapNamespace {
public:
public:
std::string name;
std::string url;
@@ -26,7 +26,7 @@ extern const SoapNamespace kSoapEnvNamespace;
// Base class for SOAP request and response.
class SoapMessage {
public:
public:
virtual ~SoapMessage() {}
// E.g., set as kSoapEnvNamespace.
@@ -52,14 +52,13 @@ public:
// Parse from SOAP request XML.
bool FromXml(const std::string& xml_string);
protected:
protected:
// Convert to SOAP body XML.
virtual void ToXmlBody(pugi::xml_node xbody) = 0;
// Parse from SOAP body XML.
virtual bool FromXmlBody(pugi::xml_node xbody) = 0;
protected:
SoapNamespace soapenv_ns_; // SOAP envelope namespace.
SoapNamespace service_ns_; // Namespace for your web service.
+3 -3
View File
@@ -11,7 +11,7 @@ namespace webcc {
// Used to compose the SOAP request envelope XML which will be sent as the HTTP
// request body.
class SoapRequest : public SoapMessage {
public:
public:
void AddParameter(const Parameter& parameter);
void AddParameter(Parameter&& parameter);
@@ -19,11 +19,11 @@ public:
// Get parameter value by key.
const std::string& GetParameter(const std::string& key) const;
protected:
protected:
void ToXmlBody(pugi::xml_node xbody) override;
bool FromXmlBody(pugi::xml_node xbody) override;
private:
private:
std::vector<Parameter> parameters_;
};
+1 -2
View File
@@ -6,8 +6,7 @@
namespace webcc {
bool SoapRequestHandler::RegisterService(SoapServicePtr service,
const std::string& url) {
bool SoapRequestHandler::Bind(SoapServicePtr service, const std::string& url) {
assert(service);
url_service_map_[url] = service;
+3 -7
View File
@@ -8,17 +8,13 @@
namespace webcc {
class SoapRequestHandler : public HttpRequestHandler {
public:
public:
SoapRequestHandler() = default;
~SoapRequestHandler() override = default;
// Register a SOAP service to the given URL path.
// The |url| path must start with "/", e.g., "/calculator".
// Registering to the same URL multiple times is allowed, but only the last
// one takes effect.
bool RegisterService(SoapServicePtr service, const std::string& url);
bool Bind(SoapServicePtr service, const std::string& url);
private:
private:
void HandleSession(HttpSessionPtr session) override;
SoapServicePtr GetServiceByUrl(const std::string& url);
+3 -3
View File
@@ -7,7 +7,7 @@ namespace webcc {
// SOAP response.
class SoapResponse : public SoapMessage {
public:
public:
// Could be "Price" for an operation/method like "GetXyzPrice".
// Really depend on the service.
// Most services use a general name "Result".
@@ -27,12 +27,12 @@ public:
result_ = std::move(result);
}
protected:
protected:
void ToXmlBody(pugi::xml_node xbody) override;
bool FromXmlBody(pugi::xml_node xbody) override;
private:
private:
// NOTE:
// Multiple results might be necessary. But for most cases, single result
// should be enough, because an API normally returns only one value.
+8 -4
View File
@@ -9,18 +9,22 @@
namespace webcc {
class SoapServer : public HttpServer {
public:
public:
SoapServer(unsigned short port, std::size_t workers)
: HttpServer(port, workers) {
}
~SoapServer() override = default;
bool RegisterService(SoapServicePtr service, const std::string& url) {
return request_handler_.RegisterService(service, url);
// Bind a SOAP service to the given URL path.
// The |url| path must start with "/", e.g., "/calculator".
// Binding to the same URL multiple times is allowed, but only the last
// one takes effect.
bool Bind(SoapServicePtr service, const std::string& url) {
return request_handler_.Bind(service, url);
}
private:
private:
HttpRequestHandler* GetRequestHandler() override {
return &request_handler_;
}
+2 -2
View File
@@ -12,14 +12,14 @@ class SoapResponse;
// Base class for your SOAP service.
class SoapService {
public:
public:
virtual ~SoapService() = default;
// Handle SOAP request, output the response.
virtual bool Handle(const SoapRequest& soap_request,
SoapResponse* soap_response) = 0;
protected:
protected:
HttpStatus::Enum http_status_ = HttpStatus::kOK;
};
+4 -5
View File
@@ -19,7 +19,7 @@ namespace webcc {
// URL query parameters.
class UrlQuery {
public:
public:
typedef std::vector<Parameter> Parameters;
UrlQuery() = default;
@@ -49,18 +49,17 @@ public:
// E.g., "item=12731&color=blue&size=large".
std::string ToString() const;
private:
private:
typedef Parameters::const_iterator ConstIterator;
ConstIterator Find(const std::string& key) const;
private:
Parameters parameters_;
};
// -----------------------------------------------------------------------------
class Url {
public:
public:
Url() = default;
Url(const std::string& str, bool decode);
@@ -88,7 +87,7 @@ public:
// Split query string into key-value parameters.
static void SplitQuery(const std::string& str, UrlQuery* query);
private:
private:
void Init(const std::string& str);
std::string path_;