blob: 03a22b049ca45b890b6e815e8f9514fd55bbd50f (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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;
}
}
|