你, 是否還在爲libcurl太難用,太底層,各種麻煩的函式與變數看不懂而困擾 ——
那麼就Try Neko Network (NekoNet) ,一個易用,高效的C++ Libcurl封裝。
準備
先決條件
- 一個支援C++20或以上的C++編譯器
- CMake 3.16+
- Git
- libcurl 8.0+
- OpenSSL 3.0+ (windows上是可選的)
透過CMake使用
- 使用CMake的
FetchContent模組與Git自動拉取:
include(FetchContent)
# Add NekoNet to your CMake project
FetchContent_Declare(
NekoNet
GIT_REPOSITORY https://github.com/moehoshio/NekoNet.git
GIT_TAG main
)
FetchContent_MakeAvailable(NekoNet)
# 你的可執行檔
add_executable(your_target main.cpp)
# 鏈接NekoNet
target_link_libraries(your_target PRIVATE Neko::Net)- 在原始碼內導入標頭
#include <neko/network/network.hpp>- 配置你的CMake專案並設定包路徑(前提是你用包管理安裝過需要的程式庫):
cmake -B ./build -DCMAKE_PREFIX_PATH=<你的包路徑> -S .如果你還沒有安裝過包管理器,那麼可以嘗試vcpkg。
透過vcpkg安裝包
# 克隆vcpkg倉庫
git clone https://github.com/microsoft/vcpkg.git
# 初始vcpkg
cd vcpkg && bootstrap-vcpkg.bat
# 安裝OpenSSL和libcurl
vcpkg install openssl curl確認
如果你成功安裝並配置好了NekoNet,大概會看到類似以下的輸出:
-- Found CURL: C:/dev/vcpkg/installed/x64-windows-static/share/curl/CURLConfig.cmake (found version "8.16.0-DEV")
-- Start configuration Neko Net...
-- NekoNet configuration summary:
-- - CMake version: 4.1.2
--
-- - Neko Net Auto fetch deps: ON
-- - Neko Net Build tests: ON
--
-- Dependency summary:
# 代表cmake找到了openssl
-- - OpenSSL support: TRUE version:
# 代表cmake找到了libcurl
-- - libcurl support: TRUE version: 8.16.0-DEV
--
-- Found OpenSSL
-- Found libcurl 8.16.0-DEV
-- Start configuration Neko Schema...
...一切準備就緒,現在可以愉快的寫程式碼啦~
這是一個基本請求例子:
#include <neko/network/network.hpp>
int main(){
using namespace neko;
// 建立一個網路對象
network::Network net;
// 拼接url : https://example.com/Hello
auto url = network::buildUrl("/Hello","example.com","https://");
network::RequestConfig reqConfig{
.method = network::RequestType::Get, // Get方法,可用Post,DownloadFile, UploadFile,Head
.url = url,
.requestId = "Main-Hello NekoNet - 1", //請求id
};
auto response = net.execute<std::string>(reqConfig);
if (response.isSuccess()) {
// 成功 並打印請求輸出
std::cout<< response.content << std::endl;
} else {
// 失敗,打印錯誤資訊
std::cout<< "Error: " << response.errorMessage << std::endl;
}
}當然了,你還可以Post,上載或下載:
enum class RequestType {
Get,
Head,
Post,
DownloadFile,
UploadFile
};只需要變更請求方法配置中的枚舉值即可,非常簡單!
也許你想下載檔案,一張圖像,或是一段文本? 只需要改動配置即可完成:
network::RequestConfig reqConfig{
.method = network::RequestType::DownloadFile, //下載到檔案
.url = url,
.requestId = "Main-" + util::random::generateRandomString(6), //設定requestId
.resumable = false, //斷點續傳
.fileName = "file.png", //下載或上傳檔案名稱
};Post和上載方法同理,設定請求配置的值即可。 每個配置你可以請求一次或者多次,乃至改動url之後繼續拿去其他請求也完全沒有問題!
只需要改動配置,並請求一兩個方法即可! 一切都很簡單。
進階
你說,有沒有更進階一點的方法? 答案是肯定的。
你仍可輕易地高度自定它!
要支援自定回調進度,你可以透過請求參數.progressCallback自定回調函式:
neko::uint64 contentSize = net.getContentSize(url).value_or(0);
...
.progressCallback = [contentSize](neko::uint64 bytesReceived) {
// 下載進度回調
std::cout << "Downloaded " << (bytesReceived * 100 / contentSize) << "% \r" << std::flush;
}透過getContentSize方法來取得目標大小(需要伺服器支援)並設定下載進度回調。
如果沒有問題,這應該會一直刷新下載進度百分比,直到結束。
requestId
請求id可以幫助您在輸出中識別某個請求,它可以是任意字串,並在日誌中列印它。
異步請求
只需要執行異步版本的函式即可: executeAsync。其與同步版本大致相同!
如果要自定異步方式(如使用自己的執行緒池,請自定executor)。
你需要繼承自neko::network::executor::IAsyncExecutor 並覆寫 submitImpl函式:
// main.cpp
class MyAsyncExecutor : public IAsyncExecutor {
protected:
template <typename R>
std::future<R> submitImpl(std::function<R()> f) {
return 你自己的異步方式(std::move(f));
}
};
int main(){
neko::network::Network net;
// 設定使用自定的Executor
neko::network::setExecutorFactory([](){
return std::make_shared<MyAsyncExecutor>();
});
// 現在將使用你自定的異步方式請求了
net.executeAsync({ .url = "htttps://example.com"});
}自定響應類型
默認情況下,響應是透過std::string返回的,(除了download file方法)。
如果要自定,只需要爲方法指定實例化模板:
auto res = execute<MyString>(cfg);
// res.content = MyString自定標頭
只需要在請求配置中設定 header即可! 並且我們默認提供了很多常見的標頭
RequestConfig reqConfig{
// 使用json標頭 Content-Type: application/json
.header = network::header::jsonContentHeader
};
// 還有可以自由拼接的Json ContentType : application/json
reqConfig.header = network::header::jsonContentType;這樣你就可以自由拼接標頭了
更多請查閱readme
已經加上咯~ 常來玩喔!
博主您好,我已在我站添加您的友链信息。下面是我的友链信息: 博客名:Modern Blog 简介:分享技术,记录生活 网站地址:https://blog.andyjin.website 头像图片:https://filestorage0.oss-cn-hongkong.aliyuncs.com/avatar.png Atom订阅:https://blog.andyjin.website/atom.xml 感谢您的添加,我们常联系!
你好呀~ 看到留言訊息裏的 ⌈O2⌋可能是拼寫錯誤,故維持了原始網域並更新了頭像路徑 如有誤可再留言變更~