root/CurlResult.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <string.h>
#include <ncurses.h>
#include <stdio.h>
#include "CurlResult.h"

void CurlResult_init(struct CurlResult* this) {
    Buffer_init(&this->buffer);
}

void CurlResult_destroyMembers(struct CurlResult* this) {
    Buffer_destroyMembers(&this->buffer);
}

size_t CurlResult_write(void* buffer, size_t charSize, size_t bufferSize, void* userdata) {
    if (!userdata) {
        return 0;
    }
    struct CurlResult* this = userdata;
    return Buffer_append(&this->buffer, buffer, (bufferSize*charSize));
}

json_value* CurlResult_parse(struct CurlResult* this) {
    /* FILE* f = fopen("jsonbuffer", "w"); */
    /* fwrite(this->buffer.buffer, sizeof(char), this->buffer.bufferUsed, f); */
    /* fclose(f); */
    char error[512] = { 0 };
    json_settings settings = { 0 };
    json_value* ret = json_parse_ex(&settings, this->buffer.buffer, this->buffer.bufferUsed, error);
    /* if (error[0] != 0) { */
    /*     printf("failed parsing json:\n  %s\n", error); */
    /*     exit(4); */
    /* } */
    return ret;
}

CURL* Curl_defaultHandle(const char* url, struct CurlResult* userdata) {
    CURL* handle = curl_easy_init();
    CurlResult_init(userdata);
    curl_easy_setopt(handle, CURLOPT_URL, url);
    curl_easy_setopt(handle, CURLOPT_TIMEOUT, 15);
    curl_easy_setopt(handle, CURLOPT_NOSIGNAL, 1);
    curl_easy_setopt(handle, CURLOPT_WRITEDATA, userdata);
    curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, CurlResult_write);
    return handle;
}

DEFAULT_CREATE_DESTROY(CurlResult)