RESTful client example [Mongoose More Than An Embedded Web Server]

0

In this blog post, I’ll show you how easy it is to implement a RESTful client with Mongoose. As always, the full source code for this example is available at GitHub. All you have to do is clone the repository and type “make” in the example directory.

How the RESTful Client Example Works

When the example is built, it produces a binary executable file that can be started from the shell:

$ ./restful_client
Starting RESTful client against 
http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=cesanta
Got reply:
{"responseData": null, "responseDetails": "The Google Web Search API is no longer available. Please migrate to the Google Custom Search API (https://developers.google.com/custom-search/)", "responseStatus": 403}

As you can see, the binary triggers a RESTful, hard-coded request to one of Google’s online services and prints the response to the terminal.

Let’s move on to the code investigation.

Code explained

This is the standard master key to initialize the event handler and create an outgoing connection:

mg_mgr_init(&mgr, NULL);
nc = mg_connect_http(&mgr, ev_handler, s_url, NULL, NULL);
mg_set_protocol_http_websocket(nc);

Then it’s the infinite event loop:

printf("Starting RESTful client against %sn", s_url);
 while (s_exit_flag == 0) {
   mg_mgr_poll(&mgr, 1000);
 }
 mg_mgr_free(&mgr);

And now the kernel; an event handler function. What should be done ? First, catch the MG_EV_CONNECT event to see if the connection to the server was successful. If not, it will display an error and stop the event loop.

Next, we handle the MG_EV_HTTP_REPLY event by printing the entire HTTP body received on the terminal. Here is the code:

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

  switch (ev) {
    case MG_EV_CONNECT:
      connect_status = *(int *) ev_data;
      if (connect_status != 0) {
       printf("Error connecting to %s: %sn", s_url,
         strerror(connect_status));
        s_exit_flag = 1;
      }
      break;
    case MG_EV_HTTP_REPLY:
      printf("Got reply:n%.*sn", (int) hm->body.len, hm->body.p);
      nc->flags |= MG_F_SEND_AND_CLOSE;
      s_exit_flag = 1;
      break;
    default:
      break;
  }
}

When the HTTP payload is printed, we also stop the event loop and exit the program.

We hope you enjoy recreating this example!

Test the example for yourself!
DOWNLOAD MONGOOSE


Source link

Share.

About Author

Leave A Reply