#ifndef HTTP_CURL
#define HTTP_CURL
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "auth.h"
// Buffer to store the response
struct ResponseBuffer {
char *data; // Pointer to the response data
size_t size; // Size of the data
};
// Callback function to handle the response
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t total_size = size * nmemb;
struct ResponseBuffer *response = (struct ResponseBuffer *)userp;
// Reallocate memory to fit new data
char *ptr = realloc(response->data, response->size + total_size + 1);
if (ptr == NULL) {
fprintf(stderr, "Failed to allocate memory for response\n");
return 0; // Returning 0 will signal libcurl to abort the request
}
// Assign the newly allocated memory to response->data
response->data = ptr;
// Copy the new data into the buffer
memcpy(&(response->data[response->size]), contents, total_size);
// Update the size of the buffer
response->size += total_size;
// Null-terminate the string
response->data[response->size] = '\0';
return total_size;
}
char * curl_post(const char * url, const char * data) {
CURL *curl;
CURLcode res;
struct ResponseBuffer response;
response.data = (char *)malloc(1);
response.size = 0;
curl = curl_easy_init();
if (curl) {
struct curl_slist *headers = NULL;
curl_easy_setopt(curl, CURLOPT_URL, url);
headers = curl_slist_append(headers, "Content-Type: application/json");
char * bearer_header = (char *)malloc(1337);
sprintf(bearer_header, "Authorization: Bearer %s", resolve_api_key());
headers = curl_slist_append(headers, bearer_header);
free(bearer_header);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
fprintf(stderr, "Error occured: %s\n", curl_easy_strerror(res));
}
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
return response.data;
}
return 0;
}
#endif