STTNet 0.7.0

Chapter 4: Requests, JSON, Responses

This chapter describes method, path, query, header, and body access, together with text, JSON, error, and redirect responses.

1. Request fields

Field / methodMeaning
typeHTTP method such as GET or POST.
locParaOriginal path plus query, for example /users?id=7.
locPath only, for example /users.
paraRaw query beginning with ?, for example ?id=7. It is not URL-decoded and is not a key/value map.
headerThe complete request-header string.
headerValue(name)Case-insensitive lookup returning a non-owning string_view.
bodyView()Unified Content-Length/chunked body view, also non-owning.

2. View Lifetime in Asynchronous Code

const std::string_view temporary = request.bodyView();
const std::string ownedBody(request.bodyView()); // Safe to retain or move.

3. Client JSON Parsing

examples/http_json.cpp demonstrates method validation, JsonCpp parsing, a 400 syntax response, a 422 field response, and a 201 success response.

const std::string body(request.bodyView());
Json::CharReaderBuilder builder;
auto reader = std::unique_ptr<Json::CharReader>(builder.newCharReader());
Json::Value input;
std::string error;
if(!reader->parse(body.data(), body.data() + body.size(), &input, &error))
    return client.sendJson(makeError("invalid JSON"), "400 Bad Request") ? 1 : -2;

4. Response helpers

client.sendText("created", "201 Created");
client.sendJson(value, "200 OK");
client.redirect("/login", "302 Found");

5. Demo Execution

./build/examples/sttnet_http_json
curl -i -X POST http://127.0.0.1:8081/json \
  -H 'Content-Type: application/json' \
  --data '{"name":"Stephen"}'
curl -i -X POST http://127.0.0.1:8081/json \
  -H 'Content-Type: application/json' --data '{bad json}'