Statistics
| Branch: | Tag: | Revision:

mongoose / examples / http_client / http_client.c @ eaef5bd1

History | View | Annotate | Download (1.72 KB)

1
/*
2
 * Copyright (c) 2014 Cesanta Software Limited
3
 * All rights reserved
4
 *
5
 * This program fetches HTTP URLs.
6
 */
7

    
8
#include "mongoose.h"
9

    
10
static int s_exit_flag = 0;
11
static int s_show_headers = 0;
12
static const char *s_show_headers_opt = "--show-headers";
13

    
14
static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
15
  struct http_message *hm = (struct http_message *) ev_data;
16

    
17
  switch (ev) {
18
    case MG_EV_CONNECT:
19
      if (*(int *) ev_data != 0) {
20
        fprintf(stderr, "connect() failed: %s\n", strerror(*(int *) ev_data));
21
        s_exit_flag = 1;
22
      }
23
      break;
24
    case MG_EV_HTTP_REPLY:
25
      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
26
      if (s_show_headers) {
27
        fwrite(hm->message.p, 1, hm->message.len, stdout);
28
      } else {
29
        fwrite(hm->body.p, 1, hm->body.len, stdout);
30
      }
31
      putchar('\n');
32
      s_exit_flag = 1;
33
      break;
34
    case MG_EV_CLOSE:
35
      if (s_exit_flag == 0) {
36
        printf("Server closed connection\n");
37
        s_exit_flag = 1;
38
      }
39
      break;
40
    default:
41
      break;
42
  }
43
}
44

    
45
int main(int argc, char *argv[]) {
46
  struct mg_mgr mgr;
47
  int i;
48

    
49
  mg_mgr_init(&mgr, NULL);
50

    
51
  /* Process command line arguments */
52
  for (i = 1; i < argc; i++) {
53
    if (strcmp(argv[i], s_show_headers_opt) == 0) {
54
      s_show_headers = 1;
55
    } else if (strcmp(argv[i], "--hexdump") == 0 && i + 1 < argc) {
56
      mgr.hexdump_file = argv[++i];
57
    } else {
58
      break;
59
    }
60
  }
61

    
62
  if (i + 1 != argc) {
63
    fprintf(stderr, "Usage: %s [%s] [--hexdump <file>] <URL>\n", argv[0],
64
            s_show_headers_opt);
65
    exit(EXIT_FAILURE);
66
  }
67

    
68
  mg_connect_http(&mgr, ev_handler, argv[i], NULL, NULL);
69

    
70
  while (s_exit_flag == 0) {
71
    mg_mgr_poll(&mgr, 1000);
72
  }
73
  mg_mgr_free(&mgr);
74

    
75
  return 0;
76
}