[C.C++] C++实现简单RESTful服务

29 0
Honkers 13 小时前 | 显示全部楼层 |阅读模式

在C++中实现RESTful服务的一种常见方法是使用HTTP服务器库和JSON解析器,例如libmicrohttpd和jsoncpp。

下面是一个使用libmicrohttpd和jsoncpp的简单RESTful服务示例。假设你的C++程序需要提供一个名为"add"的RESTful接口,它需要接收两个整数参数,并返回它们的和。这里的代码是在Linux平台下编写的。

首先,需要安装libmicrohttpd和jsoncpp库。在Ubuntu上可以使用以下命令进行安装:

  1. sudo apt-get install libmicrohttpd-dev libjsoncpp-dev
复制代码

接下来,编写一个HTTP请求处理器类,它将处理来自客户端的RESTful请求:

  1. #include <jsoncpp/json/json.h>
  2. #include <microhttpd.h>
  3. class RestRequestHandler {
  4. public:
  5. RestRequestHandler() {}
  6. int handleRequest(struct MHD_Connection *connection, const char *url, const char *method, const char *upload_data, size_t *upload_data_size) {
  7. if (strcmp(method, "GET") == 0 && strcmp(url, "/add") == 0) {
  8. int a = 0, b = 0;
  9. const char *a_str = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "a");
  10. const char *b_str = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "b");
  11. if (a_str && b_str) {
  12. a = atoi(a_str);
  13. b = atoi(b_str);
  14. }
  15. Json::Value response;
  16. response["result"] = a + b;
  17. Json::FastWriter writer;
  18. std::string responseStr = writer.write(response);
  19. struct MHD_Response *responseHandle = MHD_create_response_from_buffer(responseStr.size(), (void *) responseStr.c_str(), MHD_RESPMEM_MUST_COPY);
  20. MHD_add_response_header(responseHandle, "Content-Type", "application/json");
  21. int ret = MHD_queue_response(connection, MHD_HTTP_OK, responseHandle);
  22. MHD_destroy_response(responseHandle);
  23. return ret;
  24. } else {
  25. struct MHD_Response *responseHandle = MHD_create_response_from_data(0, nullptr, MHD_NO, MHD_YES);
  26. int ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, responseHandle);
  27. MHD_destroy_response(responseHandle);
  28. return ret;
  29. }
  30. }
  31. };
复制代码

在上面的代码中,handleRequest()方法将处理"GET /add"请求,并返回JSON格式的响应。

接下来,编写一个HTTP服务器类,它将启动HTTP服务器并监听RESTful请求:

  1. class RestServer {
  2. public:
  3. RestServer(int port) : port_(port), daemon_(nullptr), requestHandler_() {}
  4. void start() {
  5. daemon_ = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, port_, nullptr, nullptr, &RestServer::requestHandlerCallback, (void *) &requestHandler_, MHD_OPTION_END);
  6. if (daemon_ == nullptr) {
  7. throw std::runtime_error("Failed to start HTTP server.");
  8. }
  9. }
  10. void stop() {
  11. if (daemon_ != nullptr) {
  12. MHD_stop_daemon(daemon_);
  13. daemon_ = nullptr;
  14. }
  15. }
  16. private:
  17. static int requestHandlerCallback(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *upload_data, size
复制代码

注意:代码未经验证,严禁上线!

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Honkers

特级红客

关注
  • 3259
    主题
  • 36
    粉丝
  • 0
    关注
这家伙很懒,什么都没留下!

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行