diff options
| author | Murilo Ijanc <[email protected]> | 2026-07-26 12:28:10 -0300 |
|---|---|---|
| committer | Murilo Ijanc <[email protected]> | 2026-07-26 12:28:10 -0300 |
| commit | b71faa6e95a0736f1ff171e006b171467b65db90 (patch) | |
| tree | 7580c3ab515e8f50726dc68dbc240995ff4a1a4c /examples | |
| download | cpp-b71faa6e95a0736f1ff171e006b171467b65db90.tar.gz | |
Initial importv0.1.0
Diffstat (limited to 'examples')
| -rw-r--r-- | examples/cepis_lookup.cpp | 83 |
1 files changed, 83 insertions, 0 deletions
diff --git a/examples/cepis_lookup.cpp b/examples/cepis_lookup.cpp new file mode 100644 index 0000000..03a22b0 --- /dev/null +++ b/examples/cepis_lookup.cpp @@ -0,0 +1,83 @@ +/// Minimal CLI: `cepis-lookup 01001000`. +/// +/// It exists for one concrete case — quickly confirming a local instance +/// answers before pointing code at it: +/// +/// ```sh +/// cepis-lookup --base-url http://localhost:8080 01001000 +/// ``` +/// +/// A single CEP goes through the unit lookup, which carries `geo`; several go +/// through the batch, which is one request instead of N and has no `geo`. +/// +/// It is not the library's main interface; for that, include `<cepis/cepis.hpp>`. + +#include <chrono> +#include <iostream> +#include <optional> +#include <string> +#include <string_view> +#include <vector> + +#include "cepis/cepis.hpp" + +namespace { + +cepis::Json to_json(const cepis::Address& address) { + cepis::Json object = address.raw; + if (!object.is_object()) { + object = cepis::Json::object(); + } + return object; +} + +void usage() { + std::cerr << "usage: cepis-lookup [--base-url URL] [--timeout SECONDS] CEP [CEP...]\n"; +} + +} // namespace + +int main(int argc, char** argv) { + cepis::Config config; + std::vector<std::string> ceps; + + for (int i = 1; i < argc; ++i) { + const std::string_view argument = argv[i]; + if (argument == "--base-url" && i + 1 < argc) { + config.base_url = argv[++i]; + } else if (argument == "--timeout" && i + 1 < argc) { + config.timeout = + std::chrono::milliseconds(static_cast<long long>(std::stod(argv[++i]) * 1000)); + } else if (argument == "-h" || argument == "--help") { + usage(); + return 0; + } else if (!argument.empty() && argument.front() == '-') { + usage(); + return 2; + } else { + ceps.emplace_back(argument); + } + } + + if (ceps.empty()) { + usage(); + return 2; + } + + try { + const cepis::Client client(config); + if (ceps.size() == 1) { + std::cout << to_json(client.lookup(ceps.front())).dump() << '\n'; + return 0; + } + cepis::Json output = cepis::Json::array(); + for (const std::optional<cepis::Address>& address : client.lookup_many(ceps)) { + output.push_back(address ? to_json(*address) : cepis::Json{}); + } + std::cout << output.dump() << '\n'; + return 0; + } catch (const cepis::Error& error) { + std::cerr << "error: " << error.what() << '\n'; + return 1; + } +} |