Initial import
[project/uclient.git] / uclient-example.c
1 #include <libubox/blobmsg.h>
2
3 #include "uclient.h"
4
5 static void example_header_done(struct uclient *cl)
6 {
7         struct blob_attr *cur;
8         int rem;
9
10         fprintf(stderr, "Headers: \n");
11         blobmsg_for_each_attr(cur, cl->meta, rem) {
12                 fprintf(stderr, "%s=%s\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
13         }
14
15         fprintf(stderr, "Contents:\n");
16 }
17
18 static void example_read_data(struct uclient *cl)
19 {
20         char buf[256];
21         int len;
22
23         while (1) {
24                 len = uclient_read(cl, buf, sizeof(buf));
25                 if (!len)
26                         return;
27
28                 fwrite(buf, len, 1, stderr);
29         }
30 }
31
32 static void example_request_sm(struct uclient *cl)
33 {
34         static int i = 0;
35
36         switch (i++) {
37         case 0:
38                 uclient_connect(cl);
39                 uclient_http_set_request_type(cl, "HEAD");
40                 uclient_request(cl);
41                 break;
42         case 1:
43                 uclient_connect(cl);
44                 uclient_http_set_request_type(cl, "GET");
45                 uclient_request(cl);
46                 break;
47         default:
48                 uclient_free(cl);
49                 uloop_end();
50                 break;
51         };
52 }
53
54 static void example_eof(struct uclient *cl)
55 {
56         example_request_sm(cl);
57 }
58
59 static const struct uclient_cb cb = {
60         .header_done = example_header_done,
61         .data_read = example_read_data,
62         .data_eof = example_eof,
63 };
64
65 int main(int argc, char **argv)
66 {
67         struct uclient *cl;
68
69         if (argc != 2) {
70                 fprintf(stderr, "Usage: %s <URL>\n", argv[0]);
71                 return 1;
72         }
73
74         uloop_init();
75         cl = uclient_new(argv[1], &cb);
76         if (!cl) {
77                 fprintf(stderr, "Failed to allocate uclient context\n");
78                 return 1;
79         }
80         example_request_sm(cl);
81         uloop_run();
82         uloop_done();
83
84         return 0;
85 }