Skip to content

Instantly share code, notes, and snippets.

@thehydroimpulse
Last active September 11, 2016 21:14
Show Gist options
  • Save thehydroimpulse/7575626 to your computer and use it in GitHub Desktop.
Save thehydroimpulse/7575626 to your computer and use it in GitHub Desktop.
Example C++11 web server backed by libuv, http-parser, and jsonxx.
#include <functional>
#include <string>
#include <http/http.h>
class ExampleController {
public:
static void example(http::Request* request, http::Response response) {
response.send<http::html>("<html><h1>ExampleController</h1></html>");
}
static void work(http::Request* request, http::Response* response) {
// You can access the current libuv loop under `request.loop`. This allows you to do
// extra non-blocking IO/work in your routes.
//
// We provide a much easier to use syntax for doing ad-hoc non-blocking work: (using C++11)
// Queue is a wrapper around: `uv_queue_work`
request->queue([response]() {
// Do some work here.
//
// * Read some file
// * Write to some files
// * ....
response->send<http::html>("<h1>We did some non-blocking work during this request!</h1>");
})
}
};
int main(int argc, char** argv) {
// Create a new HTTP server.
http::Server* server = new http::Server();
// Register an inline route: (This uses C++11's lambda functions)
//
// @path /
// @send {json}
server.route<http::get>("/", [](http::Request* request, http::Response* response) {
// Just a simple JSON response that's formed within a string. You could also construct a JSON
// object using regular C++. Obviously a bit verbose.
response->send<http::json>("{ \"route\": \"/\", \"method\": \"get\", \"responseCode\": 200 }");
});
// You can also register a route without lambda functions. You could have a controller class
// You could also create your own controller system (instead of just using it like a namespace) by
// passing a lambda function to the routes that are registered where you'd initialize your controllers
// and load the appropriate ones.
//
// However, this does complicate things a bit and introduces more complex logic & syntax.
//
// This simple `express`-ish routing style is much simpler.
server.route<http::get>("/example", ExampleController::example);
// Start the event loop and listen on the specified host & port.
return server->listen("0.0.0.0", 8080);
}
@kishorenc
Copy link

@thehydroimpulse - What HTTP cpp library are you using in this snippet?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment