Http请求转发服务器实现

时间:2024-10-19 06:57:34
#include <iostream> #include <httplib.h> #include <string> // 定义一个简单的路由处理器 void catch_all(const httplib::Request& req, httplib::Response& res) { // 构建转发的目标 URL std::string path = req.path; std::cout << "path: " << path << std::endl; std::cout << "method: " << req.method << std::endl; std::string forward_url = "http://10.8.0.126/" + path; // 转发请求,并传递请求头、数据以及文件(如果有) httplib::Headers headers; headers = req.headers; headers.erase("Host"); // 获取请求的数据,根据请求方法选择适当的数据处理方式 std::string data; data = req.body; // 使用 httplib 客户端进行转发 httplib::Client client("10.10.112.139", 9092); httplib::Result result; if (req.method == "GET") { result = client.Get(path, headers); } else if (req.method == "POST") { result = client.Post(path, headers, data, "application/json"); std::cout << result->body << std::endl; } else if (req.method == "PUT") { result = client.Put(path, headers, data, "application/json"); } else if (req.method == "DELETE") { result = client.Delete(path, headers); } else { res.set_content("Unsupported method", "text/plain"); res.status = 405; return; } if (result && result->status == 200) { res.set_content(result->body, result->get_header_value("Content-Type")); res.status = result->status; for (const auto& header : result->headers) { res.headers.emplace(header.first, header.second); } } else { res.set_content("Forward request failed", "text/plain"); res.status = 500; } } int main() { httplib::Server svr; // 捕获所有请求并转发 svr.Get(R"(/.*)", &catch_all); svr.Post(R"(/.*)", &catch_all); auto ret = svr.set_mount_point("/", "/home/narada/ems/www"); svr.listen("0.0.0.0", 8080); return 0; }