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

Commit

Permalink
httpclient: Add ability to pass custom headers (#1251)
Browse files Browse the repository at this point in the history
httpclient: Add ability to pass custom headers
  • Loading branch information
lbonn authored Jul 15, 2019
2 parents 49d40eb + 3944e9c commit 46b2884
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
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

0 comments on commit 46b2884

Please sign in to comment.