comparison src/c/feed.c @ 0:ad85b8813e8a

Fetched a URL
author Adam Chlipala <adam@chlipala.net>
date Tue, 11 Jan 2011 10:31:48 -0500
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:ad85b8813e8a
1 #include <ctype.h>
2 #include <string.h>
3 #include <stdlib.h>
4
5 #include <curl/curl.h>
6
7 #include <feed.h>
8
9 #define BUF_INIT 1024
10 #define BUF_MAX 1073741824
11
12 uw_unit uw_FeedFfi_init(uw_context ctx) {
13 curl_global_init(CURL_GLOBAL_ALL);
14
15 return uw_unit_v;
16 }
17
18 static CURL *curl(uw_context ctx) {
19 CURL *r;
20
21 if (!(r = uw_get_global(ctx, "curl"))) {
22 r = curl_easy_init();
23 if (r)
24 uw_set_global(ctx, "curl", r, curl_easy_cleanup);
25 }
26
27 return r;
28 }
29
30 static void free_buffer(void *data) {
31 uw_buffer *buf = data;
32
33 uw_buffer_free(buf);
34 free(buf);
35 }
36
37 static uw_buffer *curl_buffer(uw_context ctx) {
38 uw_buffer *r;
39
40 if (!(r = uw_get_global(ctx, "curl_buffer"))) {
41 r = malloc(sizeof(uw_buffer));
42 if (r) {
43 uw_buffer_init(BUF_MAX, r, BUF_INIT);
44 uw_set_global(ctx, "curl_buffer", r, free_buffer);
45 }
46 }
47
48 return r;
49 }
50
51 static size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp) {
52 uw_buffer *out = userp;
53
54 uw_buffer_append(out, buffer, size * nmemb);
55
56 return size * nmemb;
57 }
58
59 uw_Basis_string uw_FeedFfi_fetch(uw_context ctx, uw_Basis_string url) {
60 CURL *c = curl(ctx);
61 uw_buffer *b = curl_buffer(ctx);
62 CURLcode code;
63
64 uw_buffer_reset(b);
65
66 curl_easy_setopt(c, CURLOPT_URL, url);
67 curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, write_data);
68 curl_easy_setopt(c, CURLOPT_WRITEDATA, b);
69
70 code = curl_easy_perform(c);
71
72 if (code)
73 uw_error(ctx, FATAL, "Error fetching URL %s", url);
74 else {
75 uw_buffer_append(b, "", 1);
76 return uw_strdup(ctx, b->start);
77 }
78 }