Research CommonsResearch Commons
cppnet/Quickstart

Quickstart

Define a handler, register a route, and understand what you still need to wire up to serve traffic.

This assumes you've completed Installation. We'll define a handler and register it with the router. To serve real traffic you'll also implement the socket layer (see the note at the end).

1. Define a handler

A handler inherits from http::handlers::BaseHandler and implements handle. Pass any shared state (like a data store) through its constructor.

#include "http/handlers/base_handler.h"
#include "http/request.h"
#include <nlohmann/json.hpp>
#include <unordered_map>
 
using UserStore = std::unordered_map<std::string, nlohmann::json>;
 
class UserPostHandler : public http::handlers::BaseHandler {
public:
    UserPostHandler(UserStore &store) : users(store) {}
 
    std::string handle(const http::Request &req) const override {
        nlohmann::json resp;
        try {
            nlohmann::json posted = nlohmann::json::parse(req.body);
            std::string username = posted["username"].get<std::string>();
            users[username] = posted;
            resp["success"] = true;
            resp["user"] = posted;
        } catch (const std::exception &e) {
            resp["success"] = false;
            resp["error"] = "Invalid JSON or missing username";
        }
        return resp.dump(2);
    }
 
private:
    UserStore &users;
};

2. Register a route

Create the router, instantiate the handler, and map a method + path to it. A shared_ptr lets one handler instance serve many requests.

#include "http/router.h"
#include <memory>
 
int main() {
    http::Router router;
    UserStore user_data_store;
 
    auto user_post_handler = std::make_shared<UserPostHandler>(user_data_store);
 
    router.add_route(
        http::Method::POST,
        "/user",
        [user_post_handler](const http::Request &req) {
            return user_post_handler->handle(req);
        }
    );
 
    // ... server startup (socket layer) goes here ...
}

3. Wire up I/O

Socket layer required

cppnet does not yet ship a socket layer. To accept connections and feed raw bytes into the parser, implement one (for example with Asio). The Request lifecycle shows exactly where it slots in.

Next