fix connect error handling
[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         static int retries;
59
60         if (retries < 10 && uclient_http_redirect(cl)) {
61                 retries++;
62                 return;
63         }
64
65         retries = 0;
66         example_request_sm(cl);
67 }
68
69 static const struct uclient_cb cb = {
70         .header_done = example_header_done,
71         .data_read = example_read_data,
72         .data_eof = example_eof,
73 };
74
75 int main(int argc, char **argv)
76 {
77         struct uclient *cl;
78
79         if (argc != 2) {
80                 fprintf(stderr, "Usage: %s <URL>\n", argv[0]);
81                 return 1;
82         }
83
84         uloop_init();
85         cl = uclient_new(argv[1], &cb);
86         if (!cl) {
87                 fprintf(stderr, "Failed to allocate uclient context\n");
88                 return 1;
89         }
90         example_request_sm(cl);
91         uloop_run();
92         uloop_done();
93
94         return 0;
95 }