http_client.c
Go to the documentation of this file.
00001 // Copyright (c) 2014 Cesanta Software
00002 // All rights reserved
00003 //
00004 // This example demostrates how to connect to the remote Web server,
00005 // download data, process it and send back a reply.
00006 
00007 #include <signal.h>
00008 #include <stdlib.h>
00009 
00010 #include "mongoose.h"
00011 
00012 static int s_received_signal = 0;
00013 static struct mg_server *s_server = NULL;
00014 static const char *s_remote_addr = "glosbe.com:80";
00015 
00016 static void signal_handler(int sig_num) {
00017   signal(sig_num, signal_handler);
00018   s_received_signal = sig_num;
00019 }
00020 
00021 static int ev_handler(struct mg_connection *conn, enum mg_event ev) {
00022   struct mg_connection *client, *orig;
00023 
00024   switch (ev) {
00025     case MG_AUTH:
00026       return MG_TRUE;
00027 
00028     case MG_CONNECT:
00029       // Send request to the remote host.
00030       // TODO(lsm): handle connect error here.
00031       mg_printf(conn, "GET %s HTTP/1.0\r\nHost: %s\r\n\r\n",
00032                 "/gapi/translate?from=eng&dest=fra&format=json&phrase=cat",
00033                 s_remote_addr);
00034       return MG_TRUE;
00035 
00036     case MG_REPLY:
00037       // Send reply to the original connection
00038       orig = (struct mg_connection *) conn->connection_param;
00039       mg_send_status(orig, conn->status_code);
00040       mg_send_header(orig, "Content-Type", "text/plain");
00041       mg_send_data(orig, conn->content, conn->content_len);
00042       mg_send_data(orig, "", 0);  // Last chunk: mark the end of reply
00043 
00044       // Disconnect connections
00045       orig->connection_param = NULL;
00046       conn->connection_param = NULL;
00047       return MG_TRUE;
00048 
00049     case MG_REQUEST:
00050       if ((client = mg_connect(s_server, s_remote_addr)) != NULL) {
00051         // Interconnect requests
00052         client->connection_param = conn;
00053         conn->connection_param = client;
00054         return MG_MORE;
00055       } else {
00056         mg_printf_data(conn, "%s", "cannot send API request");
00057         return MG_TRUE;
00058       }
00059 
00060     default:
00061       return MG_FALSE;
00062   }
00063 }
00064 
00065 int main(void) {
00066   s_server = mg_create_server(NULL, ev_handler);
00067 
00068   mg_set_option(s_server, "listening_port", "8080");
00069 
00070   // Setup signal handlers
00071   signal(SIGTERM, signal_handler);
00072   signal(SIGINT, signal_handler);
00073 
00074   printf("Listening on port %s\n", mg_get_option(s_server, "listening_port"));
00075   while (s_received_signal == 0) {
00076     mg_poll_server(s_server, 1000);
00077   }
00078   mg_destroy_server(&s_server);
00079   printf("Existing on signal %d\n", s_received_signal);
00080 
00081   return EXIT_SUCCESS;
00082 }


rc_visard_driver
Author(s): Heiko Hirschmueller , Christian Emmerich , Felix Ruess
autogenerated on Thu Jun 6 2019 20:43:04