#pragma once #include #include #include #include #include #include class CurlUrlException : public std::exception { public: CurlUrlException(CURLUcode code_) : code(code_) { #if !CURL_AT_LEAST_VERSION(7, 80, 0) snprintf(this->_id_buf, 64, "curl url error %d", this->code); #endif } const char* what() const noexcept { #if CURL_AT_LEAST_VERSION(7, 80, 0) return curl_url_strerror(this->code); #else return this->_id_buf; #endif } CURLUcode code; private: #if !CURL_AT_LEAST_VERSION(7, 80, 0) char _id_buf[64]; #endif }; using CurlStr = std::unique_ptr; class CurlUrl { public: CurlUrl(const CurlUrl&) = delete; CurlUrl& operator=(const CurlUrl&) = delete; CurlUrl() { this->_ptr = curl_url(); if (!this->_ptr) { throw std::bad_alloc(); } } ~CurlUrl() { curl_url_cleanup(this->_ptr); } constexpr CURLU* get() const noexcept { return this->_ptr; } CurlStr get(CURLUPart part, unsigned int flags = 0) const { char* content; CURLUcode code = curl_url_get(this->_ptr, part, &content, flags); if (code) { throw CurlUrlException(code); } return CurlStr(content, curl_free); } void set(CURLUPart part, const char* content, unsigned int flags = 0) { CURLUcode code = curl_url_set(this->_ptr, part, content, flags); if (code) { throw CurlUrlException(code); } } void set(CURLUPart part, const std::string& content, unsigned int flags = 0) { this->set(part, content.c_str(), flags); } private: CURLU* _ptr; };