What is HTTP?

As the communication foundation for the World Wide Web, Hypertext Transfer Protocol (HTTP) is easily the most important protocol today. With it, you define how messages are formatted, transmitted and what actions should be taken in response to commands.

HTTP includes hypertext and therefore the concept that files can contain logical links referencing other files. HTTP is the protocol that will exchange or transfer this hypertext.

It was developed initially by Tim Berners-Lee at CERT in 1989. Together, the Internet Engineering Task Force and World Wide Web Consortium coordinated the standards associated with HTTP.

Why is HTTP important for connectivity?

Although HTTP was not originally designed for the embedded space, it is now unthinkable to run without it. HTTP support gives embedded devices an opportunity to use any service that exists and uses a HTTP or protocol based on it.

When it comes to microcontrollers, HTTP is simple enough to work with them. Be aware that some features may be too heavy for small chips. However, that doesn’t mean HTTP is useless here. For example, MCUs can work with clouds, report their states and errors via HTTP or even send files if the embedded device is powerful and resourceful enough.

HTTP and Mongoose Embedded Web Server

In terms of HTTP, Mongoose supports a huge amount of features. It includes a HTTP Client and HTTP Server. Sending and receiving files (of any size), CGI, cookie auth, restful client and server and much more.

We’ve ensured that most features are extremely simple to use. Just call mg_set_protocol_http_websocket for the connection and your HTTP connection is set up. An event handler will receive new HTTP-specific events and simply handle them for you.

In addition, Mongoose provides a lot of helpers, for example, for parsing HTTP headers, serving files, parsing and composing addresses.

HTTP server example

1. Create listening connection:
mg_http_listen(&mgr, "", fn, NULL);
2. Handle incoming requests:
static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
  if (ev == MG_EV_HTTP_MSG) {
    struct mg_http_message *hm = (struct mg_http_message *) ev_data;
    if (mg_http_match_uri(hm, "/api/v1/devices")) {
See full HTTP/RESTful server example.

HTTP client example

This is a simple example: a HTTP client. Yes, you can now make HTTP requests as well as serve them. The client is asynchronous and uses the same event handling paradigm. Take a look:

mg_http_connect(&mgr, "", fn, NULL);
When response arrives, we get an event:
static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
  if (ev == MG_EV_HTTP_MSG) {
    struct mg_http_message *hm = (struct mg_http_message *) ev_data;
    printf("%.*s", (int) hm->message.len, hm->message.ptr);
See full HTTP client example.