Fork me on GitHub

Hello world example

Here is a simple hello world example serving the string {"message":"hello world."} at the route /hello.

#include <silicon/api.hh>
#include <silicon/backends/mhd.hh>
#include "symbols.hh"

using namespace sl; // Silicon namespace
using namespace s; // Symbols namespace

// Define the API:
auto hello_api = http_api(

  // The hello world procedure.
  GET / _hello = [] () { return D(_message = "Hello world."); }

);

int main()
{
  // Serve hello_api via microhttpd using the json format:
  sl::mhd_json_serve(hello_api, 12345);
}

All the variables starting with _ are called symbols. They are the core of the static paradigm of the framework. To generate their definition, use the iod_generate_symbols tool provided by the iod library and located in the directory __YOUR__INSTALL__PREFIX__/bin:

iod_generate_symbols hello_world.cc symbols.hh

Have a look at the file symbols.hh, it should contain the definitions of the symbols _hello and _message:

// Generated by iod_generate_symbols.
#include <iod/symbol.hh>
#ifndef IOD_SYMBOL_hello
#define IOD_SYMBOL_hello
    iod_define_symbol(hello)
#endif

#ifndef IOD_SYMBOL_message
#define IOD_SYMBOL_message
    iod_define_symbol(message)
#endif

The code is straitforward, exept the D function that may look a little magic. It actually defines plain C++ objects such that:

auto o = D(_attr1 = 12, _attr2 = "test");
// is equivalent to:
struct { int attr1; std::string attr2; } o{12, "test"};

The only difference is that objects created via D are introspectable at compile time. It allows the iod library to generate a specialized and optimized JSON serializer for each object type.

Note that the hello_api is not tied to microhttpd, so it can be served via any other low level network library and any serialization format.

The sl::mhdjsonserve routine setups the json serialization/deserialization and the microhttpd server.

Compilation

To compile the server:

clang++ -std=c++14 -I __YOUR__INSTALL__PREFIX__/include hello_world.cc -lmicrohttpd -o hello_world

Test

In a terminal, run the server

$ ./hello_world

In another terminal, test it with curl

$ curl "http://127.0.0.1:12345/hello"
{"message":"Hello world."}