43 lines
1.3 KiB
C
43 lines
1.3 KiB
C
#include "cell.h"
|
|
#define PAR_EASYCURL_IMPLEMENTATION
|
|
#include "par_easycurl.h"
|
|
#include <string.h>
|
|
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
|
|
// Performs a blocking HTTP GET and returns a QuickJS Blob of the body
|
|
static JSValue js_fetch_picoparser(JSContext *ctx, JSValueConst this_val,
|
|
int argc, JSValueConst *argv) {
|
|
if (argc < 1 || !JS_IsString(argv[0]))
|
|
return JS_ThrowTypeError(ctx, "fetch: URL string required");
|
|
|
|
const char *url = JS_ToCString(ctx, argv[0]);
|
|
if (!url) return JS_ThrowTypeError(ctx, "fetch: invalid URL");
|
|
|
|
par_byte *data = NULL;
|
|
int nbytes = 0;
|
|
if (!par_easycurl_to_memory(url, &data, &nbytes)) {
|
|
JS_FreeCString(ctx, url);
|
|
return JS_ThrowTypeError(ctx, "fetch: failed to fetch URL");
|
|
}
|
|
|
|
JS_FreeCString(ctx, url);
|
|
|
|
// Return a Blob wrapping the data
|
|
JSValue blob = js_new_blob_stoned_copy(ctx, data, (size_t)nbytes);
|
|
free(data); // par_easycurl allocates with malloc, so we free it
|
|
return blob;
|
|
}
|
|
|
|
static const JSCFunctionListEntry js_http_funcs[] = {
|
|
JS_CFUNC_DEF("fetch", 2, js_fetch_picoparser),
|
|
};
|
|
|
|
JSValue js_http_use(JSContext *js) {
|
|
par_easycurl_init(0); // Initialize curl
|
|
JSValue obj = JS_NewObject(js);
|
|
JS_SetPropertyFunctionList(js, obj, js_http_funcs,
|
|
sizeof(js_http_funcs)/sizeof(js_http_funcs[0]));
|
|
return obj;
|
|
}
|