Skip to content
This repository has been archived by the owner on May 21, 2024. It is now read-only.

httpclient: Add ability to pass custom headers #1251

Merged
merged 1 commit into from
Jul 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/libaktualizr/http/httpclient.cc
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ static size_t writeString(void* contents, size_t size, size_t nmemb, void* userp
return size * nmemb;
}

HttpClient::HttpClient() : user_agent(std::string("Aktualizr/") + aktualizr_version()) {
HttpClient::HttpClient(const std::vector<std::string>* extra_headers)
: user_agent(std::string("Aktualizr/") + aktualizr_version()) {
curl = curl_easy_init();
if (curl == nullptr) {
throw std::runtime_error("Could not initialize curl");
Expand All @@ -65,6 +66,12 @@ HttpClient::HttpClient() : user_agent(std::string("Aktualizr/") + aktualizr_vers

headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "Accept: */*");

if (extra_headers != nullptr) {
for (const auto& header : *extra_headers) {
headers = curl_slist_append(headers, header.c_str());
}
}
curlEasySetoptWrapper(curl, CURLOPT_HTTPHEADER, headers);
curlEasySetoptWrapper(curl, CURLOPT_USERAGENT, user_agent.c_str());
}
Expand Down
2 changes: 1 addition & 1 deletion src/libaktualizr/http/httpclient.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class CurlGlobalInitWrapper {

class HttpClient : public HttpInterface {
public:
HttpClient();
HttpClient(const std::vector<std::string> *extra_headers = nullptr);
HttpClient(const HttpClient & /*curl_in*/);
~HttpClient() override;
HttpResponse get(const std::string &url, int64_t maxsize) override;
Expand Down
8 changes: 8 additions & 0 deletions src/libaktualizr/http/httpclient_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ TEST(GetTest, get_performed) {
EXPECT_EQ(response["path"].asString(), path);
}

TEST(GetTestWithHeaders, get_performed) {
std::vector<std::string> headers = {"Authorization: Bearer token"};
HttpClient http(&headers);
std::string path = "/auth_call";
Json::Value response = http.get(server + path, HttpInterface::kNoLimit).getJson();
EXPECT_EQ(response["status"].asString(), "good");
}

/* Reject http GET responses that exceed size limit. */
TEST(GetTest, download_size_limit) {
HttpClient http;
Expand Down