Skip to content
Plaristote edited this page Feb 8, 2019 · 5 revisions

Params

The Crails::Params object is used to provide data about the http query to the user. It gives you access to the query headers, parameters and uploaded files.

DataTree

The DataTree class is an API built upon boost's property_tree. It allows you to store and retrieve value from their path:

DataTree datatree;

datatree["user"]["firstname"] = "Francis";
datatree["user"]["lastname"] = "Huster";
cout << datatree["user"].to_json() << endl; // Displays: { "firstname": "Francis", "lastname": "Huster" }

Since it uses a property_tree, you can also minimize the impact of using a DataTree by not using the operator[] when it isn't necessary:

datatree["user.firstname"] = "Francis";

See the documentation for the DataTree object.

Parameters

All the parameters collected in the url and the body of the request are provided to you through the root of the Params object. Here's an example displaying an uri parameter that is provided by the request GET /route?param=value HTTP/1.1:

using namespace Crails;

void Router::initialize()
{
  match("GET", "/route", [](Params& params)
  {
    std::cout << "`route` was called with param=" << params["param"].as<string>() << std::endl;
  });
}

Uploaded files

The uploaded files are temporarily stored on the filesystem. The Params object comes with the uploaded_file method, which allows you to look for uploaded files, and get the upload data (such as the location of the uploaded file on the filesystem, or the original name of the file).

Here's an exemple of handler displaying data about a file upload:

void route_endpoint(Crails::Params& params)
{
  const Crails::Params::File* avatar_file = params.get_upload("avatar");

  if (avatar_file)
  {
    std::cout << "The request contained a file upload named 'avatar'" << std::endl;
    std::cout << "Stored on filesystem at: " << avatar_file->temporary_path << std::endl;
    std::cout << "Mimetype: " << avatar_file->mimetype << std::endl;
    std::cout << "Original filename: " << avatar_file->name << std::endl;
  }
  else
    std::cout << "No file upload named 'avatar'" << std::endl;
}