Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "curl/curl.h"
- class Response
- {
- typedef uint16_t HttpCode;
- std::string response;
- HttpCode code;
- public:
- explicit Response(const std::string &str):
- response(str)
- {}
- };
- static const uint32_t REQUEST_TIMEOUT_MS = 30000;
- static const uint32_t CONNECT_TIMEOUT_MS = 5000;
- static const char *DOCKER_URL_BASE = "http://localhost";
- static const char *DOCKER_SOCK = "unix:/var/run/docker.sock";
- class DockerClient
- {
- static void cleanupCurlContext(void *ptr) {
- curl_easy_cleanup(static_cast<CURL*>(ptr));
- }
- std::unique_ptr<CURL, cleanupCurlContext> m_ctx;
- std::string socketPath;
- private:
- DockerClient(const Client &) = delete;
- DockerClient(const Client &&) = delete;
- DockerClient &operator =(const Client &) = delete;
- DockerClient &&operator =(const Client &&) = delete;
- typedef CURLerror ClientError;
- typedef CURLopt CurlOption;
- bool isCurlSuccess(ClientError e) {
- return e != CURLE_OK;
- }
- inline CurlError setOption(CurlOption opt, void *val) {
- return curl_easy_setopt(m_ctx, opt, param);
- }
- inline CurlError perform() {
- return curl_easy_perform(m_ctx);
- }
- public:
- DockerClient(std::string socketPath) {
- m_socketPath = socketPath;
- m_ctx = curl_easy_init();
- reset();
- }
- reset() {
- curl_easy_reset(m_ctx);
- setOption(CURLOPT_UNIX_SOCKET_PATH, m_socketPath)
- setOption(CURLOPT_TIMEOUT_MS, REQUEST_TIMEOUT_MS);
- setOption(CURLOPT_CONNECTTIMEOUT_MS, CONNECT_TIMEOUT_MS);
- }
- void setVerbose(bool verbose) {
- const CurlError res = setOption(CURLOPT_VERBOSE, verbose ? 1L : 0L);
- }
- Response get(std::string path) {
- return sendRequest("GET", path);
- }
- Response post(std::string path, std::string body) {
- return sendRequest("POST", path, body);
- }
- Response del(std::string path) {
- return sendRequest("DELETE", path);
- }
- Response sendRequest(std::string method, std::string path, std::string body = "") {
- if (method == "GET") {
- setOption(CURLOPT_HTTPGET, 1L);
- }
- else if (method == "POST") {
- setOption(CURLOPT_POST, 1L);
- setOption(CURLOPT_POSTFIELDS, body);
- }
- else if (method == "DELETE") {
- setOption(CURLOPT_CUSTOMREQUEST, "DELETE")
- }
- res = setOption(CURLOPT_URL, (std::string(DOCKER_URL_BASE) + "/" + path).c_str());
- res = perform();
- }
- };
- class GlobalCurl
- {
- public:
- GlobalCurl() {
- curl_global_init();
- }
- ~GlobalCurl() {
- curl_global_cleanup();
- }
- }
- int main()
- {
- GlobalCurl curlGlobal;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement