coyote/curlu_wrapper.h

78 lines
1.7 KiB
C
Raw Normal View History

2023-11-29 11:36:52 +00:00
#pragma once
#include <cstdio>
#include <string>
#include <memory>
#include <exception>
#include <stdexcept>
#include <curl/curl.h>
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<char, decltype(&curl_free)>;
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;
};