在C++中实现RESTful服务的一种常见方法是使用HTTP服务器库和JSON解析器,例如libmicrohttpd和jsoncpp。
下面是一个使用libmicrohttpd和jsoncpp的简单RESTful服务示例。假设你的C++程序需要提供一个名为"add"的RESTful接口,它需要接收两个整数参数,并返回它们的和。这里的代码是在Linux平台下编写的。
首先,需要安装libmicrohttpd和jsoncpp库。在Ubuntu上可以使用以下命令进行安装: - sudo apt-get install libmicrohttpd-dev libjsoncpp-dev
复制代码
接下来,编写一个HTTP请求处理器类,它将处理来自客户端的RESTful请求: - #include <jsoncpp/json/json.h>
- #include <microhttpd.h>
- class RestRequestHandler {
- public:
- RestRequestHandler() {}
- int handleRequest(struct MHD_Connection *connection, const char *url, const char *method, const char *upload_data, size_t *upload_data_size) {
- if (strcmp(method, "GET") == 0 && strcmp(url, "/add") == 0) {
- int a = 0, b = 0;
- const char *a_str = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "a");
- const char *b_str = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "b");
- if (a_str && b_str) {
- a = atoi(a_str);
- b = atoi(b_str);
- }
- Json::Value response;
- response["result"] = a + b;
- Json::FastWriter writer;
- std::string responseStr = writer.write(response);
- struct MHD_Response *responseHandle = MHD_create_response_from_buffer(responseStr.size(), (void *) responseStr.c_str(), MHD_RESPMEM_MUST_COPY);
- MHD_add_response_header(responseHandle, "Content-Type", "application/json");
- int ret = MHD_queue_response(connection, MHD_HTTP_OK, responseHandle);
- MHD_destroy_response(responseHandle);
- return ret;
- } else {
- struct MHD_Response *responseHandle = MHD_create_response_from_data(0, nullptr, MHD_NO, MHD_YES);
- int ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, responseHandle);
- MHD_destroy_response(responseHandle);
- return ret;
- }
- }
- };
复制代码
在上面的代码中,handleRequest()方法将处理"GET /add"请求,并返回JSON格式的响应。
接下来,编写一个HTTP服务器类,它将启动HTTP服务器并监听RESTful请求: - class RestServer {
- public:
- RestServer(int port) : port_(port), daemon_(nullptr), requestHandler_() {}
- void start() {
- daemon_ = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, port_, nullptr, nullptr, &RestServer::requestHandlerCallback, (void *) &requestHandler_, MHD_OPTION_END);
- if (daemon_ == nullptr) {
- throw std::runtime_error("Failed to start HTTP server.");
- }
- }
- void stop() {
- if (daemon_ != nullptr) {
- MHD_stop_daemon(daemon_);
- daemon_ = nullptr;
- }
- }
- private:
- static int requestHandlerCallback(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *upload_data, size
复制代码
注意:代码未经验证,严禁上线! |