Uniform resource identifiers (URIs) are, as you probably already know, structured strings that are used to specifically identify various entities in the world. In the domain of HTTP and REST, they are used to identify the protocol to use (HTTP or HTTPS), the
server and port (service) to contact, the resource on that service to act on or retrieve, and parameters in the form of a query. URIs used with HTTP have the following format:
protocol : // server [: port] / path ? query # fragment
where the path is a sequence of strings broken up by ‘/’ characters, and the query is a sequence of ‘name=value’ associations separated by ampersand characters.
Casablanca has comprehensive support for URI construction and use: since URIs consist of components that have different meanings, processing URIs without a class to represent them would require you to do a lot of parsing of strings. It’s better to leave that
parsing to libraries.
The core class is web::uri
, which represents a fully formed identifier. Since we expect these to be passed around and shared a lot, we wanted to make it really efficient to do so, so this class is immutable. In other words,
once the identifier has been formed, its components cannot be altered. To change it, you have to create a new instance.
A URI instance may be created directly from a (platform-independent
URIs may not contain certain characters in certain places. For example, whitespace in the middle of a URI is not valid, but it may sometimes be called for. The URI standard defines a mechanism to escape such characters, called URI encoding, and the URI class
has support for encoding, for example, the space in “path1 “ here:
If you need to incrementally create a URI, the best API to use is the uribuilder class, also in the ‘http’ namespace. Unlike the uri class, uri
builder allows you to modify components to your heart’s content, and then create a uri instance when you are
done. It is often not necessary to use a uri_builder, but it is the ultimately flexible way to go.
You can create a builder from an existing URI you have, or create an empty builder:
Once you have a builder instance, you can modify its components one by one:
You can also append to an already defined path or query:
When you are using a uri_builder, you don’t have to worry about the path and query separators, that’s taken care of for you!