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