為了實現一個包含靜態文件輸出、GET、POST 請求處理(含參數讀取)、文件上傳和下載功能的 Web API 服務,我們將使用 cpp-httplib 作為 HTTP 伺服器庫。首先,確保你已經安裝了該庫。 git clone https://github.com/yhirose/cpp-httpl ...
為了實現一個包含靜態文件輸出、GET、POST 請求處理(含參數讀取)、文件上傳和下載功能的 Web API 服務,我們將使用 cpp-httplib 作為 HTTP 伺服器庫。首先,確保你已經安裝了該庫。
git clone https://github.com/yhirose/cpp-httplib.git
cd cpp-httplib
mkdir build
cd build
cmake ..
make
sudo make install
下麵是一個簡單的示例代碼,演示如何使用 cpp-httplib 創建一個包含上述功能的 Web API 服務。
#include <httplib.h>
#include <iostream>
using namespace httplib;
int main() {
// 創建 HTTP 伺服器實例
Server svr;
// 處理靜態文件請求,將當前目錄下的 "static" 文件夾作為靜態文件根目錄
svr.set_base_dir("./static");
// 處理 GET 請求
svr.Get("/hello", [](const Request& req, Response& res) {
res.set_content("Hello, World!", "text/plain");
});
// 處理帶參數的 GET 請求
svr.Get("/greet", [](const Request& req, Response& res) {
auto name = req.get_param_value("name");
if (!name.empty()) {
res.set_content("Hello, " + name + "!", "text/plain");
} else {
res.set_content("Hello, Guest!", "text/plain");
}
});
// 處理 POST 請求
svr.Post("/echo", [](const Request& req, Response& res) {
res.set_content(req.body, "text/plain");
});
// 處理帶參數的 POST 請求
svr.Post("/greet_post", [](const Request& req, Response& res) {
auto name = req.get_param_value("name");
if (!name.empty()) {
res.set_content("Hello, " + name + "!", "text/plain");
} else {
res.set_content("Hello, Guest!", "text/plain");
}
});
// 處理文件上傳
svr.Post("/upload", [&](const Request& req, Response& res) {
auto file = req.get_file_value("file");
if (file) {
// 將上傳的文件保存到伺服器端
file->save("./uploads/" + file->filename);
res.set_content("File uploaded successfully", "text/plain");
} else {
res.set_content("File upload failed", "text/plain");
}
});
// 處理文件下載
svr.Get("/download", [&](const Request& req, Response& res) {
// 將伺服器端的文件發送給客戶端
res.download("./uploads/example.txt");
});
// 啟動伺服器,監聽埠為 8080
svr.listen("localhost", 8080, [](const Request& req, Response& res) {
// 日誌記錄,可根據實際需要擴展
std::cout << req.method << " " << req.path << std::endl;
});
return 0;
}
在這個示例中,我們使用 get_param_value 和 get_file_value 方法從請求中獲取參數和文件。get_param_value 用於獲取 GET 或 POST 請求中的參數,而 get_file_value 用於獲取上傳的文件。
請確保在使用此示例代碼時根據你的實際需求調整路徑和其他設置。這隻是一個基本的示例,生產環境中可能需要更多的安全性和錯誤處理。