Add a simple get() func using libcurl
This commit is contained in:
@@ -6,15 +6,22 @@ set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
find_package(Qt6 REQUIRED COMPONENTS Widgets)
|
||||
find_package(CURL REQUIRED)
|
||||
|
||||
qt_standard_project_setup()
|
||||
|
||||
add_executable(CrabCrawler
|
||||
src/main.cpp
|
||||
|
||||
src/ui/navbar.cpp
|
||||
src/ui/content.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(CrabCrawler
|
||||
PRIVATE Qt6::Widgets
|
||||
${CURL_LIBRARIES}
|
||||
)
|
||||
|
||||
target_link_libraries(CrabCrawler
|
||||
PRIVATE Qt6::Widgets
|
||||
)
|
||||
|
||||
46
src/util/http.c
Normal file
46
src/util/http.c
Normal file
@@ -0,0 +1,46 @@
|
||||
#include <curl/curl.h>
|
||||
|
||||
struct HttpResponse
|
||||
{
|
||||
long status;
|
||||
char *body;
|
||||
};
|
||||
|
||||
static size_t write_callback(void *ptr, size_t size, size_t nmemb, void *userdata)
|
||||
{
|
||||
size_t total = size * nmemb;
|
||||
struct HttpResponse *resp = (struct HttpResponse *)userdata;
|
||||
|
||||
size_t old_len = resp->body ? strlen(resp->body) : 0;
|
||||
char *new_body = (char *)realloc(resp->body, old_len + total + 1);
|
||||
if (!new_body)
|
||||
return 0;
|
||||
|
||||
resp->body = new_body;
|
||||
memcpy(resp->body + old_len, ptr, total);
|
||||
resp->body[old_len + total] = '\0';
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
struct HttpResponse get(const char *url)
|
||||
{
|
||||
struct HttpResponse resp = {0, NULL};
|
||||
|
||||
CURL *curl = curl_easy_init();
|
||||
if (!curl)
|
||||
return resp;
|
||||
|
||||
resp.body = (char *)malloc(1);
|
||||
resp.body[0] = '\0';
|
||||
|
||||
curl_easy_setopt(curl, CURLOPT_URL, url);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &resp);
|
||||
|
||||
curl_easy_perform(curl);
|
||||
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &resp.status);
|
||||
|
||||
curl_easy_cleanup(curl);
|
||||
return resp;
|
||||
}
|
||||
Reference in New Issue
Block a user