56 lines
2.1 KiB
C++
56 lines
2.1 KiB
C++
#include "google/adk/remote_http.h"
|
|||
|
|
|
||
|
|
#include "google/adk/caps.h"
|
||
|
|
#include "google/adk/error.h"
|
||
|
|
|
||
|
|
namespace molo::google::adk {
|
||
|
|
|
||
|
|
RemoteHttp::RemoteHttp(std::shared_ptr<clients::Client> http,
|
||
|
|
std::map<std::string, std::string> headers)
|
||
|
|
: http_(std::move(http)), headers_(std::move(headers)) {
|
||
|
|
if (!http_) throw AdkError::invalid("RemoteHttp needs a client");
|
||
|
|
}
|
||
|
|
|
||
|
|
bool RemoteHttp::valid_url(const std::string& url) {
|
||
|
|
bool scheme = url.rfind("http://", 0) == 0 || url.rfind("https://", 0) == 0;
|
||
|
|
if (!scheme || url.size() > 2048) return false;
|
||
|
|
for (char c : url)
|
||
|
|
if (c <= ' ' || c == 0x7f) return false;
|
||
|
|
return url.size() > url.find("//") + 2; // A host must follow the scheme.
|
||
|
|
}
|
||
|
|
|
||
|
|
RemoteReply RemoteHttp::finish(const std::string& url, clients::ClientRequest req) {
|
||
|
|
for (const auto& [k, v] : headers_) req.header(k, v);
|
||
|
|
clients::ClientResponse res;
|
||
|
|
try {
|
||
|
|
res = http_->send_blocking(std::move(req));
|
||
|
|
} catch (const std::exception& e) {
|
||
|
|
throw AdkError("upstream", "request failed: " + std::string(e.what()));
|
||
|
|
}
|
||
|
|
if (!res.is_success())
|
||
|
|
throw AdkError("upstream", "HTTP " + std::to_string(res.status()) + " from " + url);
|
||
|
|
if (res.body().size() > AdkCaps::kMaxHttpBodyBytes)
|
||
|
|
throw AdkError("protocol", "response over the body cap");
|
||
|
|
return {res.status(), res.headers(), res.body()};
|
||
|
|
}
|
||
|
|
|
||
|
|
RemoteReply RemoteHttp::post_json(const std::string& url,
|
||
|
|
const clients::body::Json& body,
|
||
|
|
const std::map<std::string, std::string>& extra) {
|
||
|
|
if (!valid_url(url)) throw AdkError::invalid("invalid url");
|
||
|
|
clients::ClientRequest req = clients::ClientRequest::post(url);
|
||
|
|
req.json(body);
|
||
|
|
for (const auto& [k, v] : extra) req.header(k, v);
|
||
|
|
return finish(url, std::move(req));
|
||
|
|
}
|
||
|
|
|
||
|
|
RemoteReply RemoteHttp::get(const std::string& url,
|
||
|
|
const std::map<std::string, std::string>& extra) {
|
||
|
|
if (!valid_url(url)) throw AdkError::invalid("invalid url");
|
||
|
|
clients::ClientRequest req = clients::ClientRequest::get(url);
|
||
|
|
for (const auto& [k, v] : extra) req.header(k, v);
|
||
|
|
return finish(url, std::move(req));
|
||
|
|
}
|
||
|
|
|
||
|
|
} // namespace molo::google::adk
|