Remove HttpFile to FormPart; refine payload prepare.

This commit is contained in:
Chunting Gu
2019-04-12 14:18:23 +08:00
parent 80d0c73617
commit a96109c3b7
24 changed files with 451 additions and 316 deletions
+107
View File
@@ -6,14 +6,28 @@
#include <utility>
#include <vector>
#include "boost/asio/buffer.hpp" // for const_buffer
#include "boost/filesystem/path.hpp"
#include "webcc/globals.h"
namespace webcc {
// -----------------------------------------------------------------------------
using Path = boost::filesystem::path;
using Payload = std::vector<boost::asio::const_buffer>;
// -----------------------------------------------------------------------------
// Split a string to two parts by the given token.
bool Split2(const std::string& str, char token, std::string* part1,
std::string* part2);
// Read entire file into string.
bool ReadFile(const Path& path, std::string* output);
// -----------------------------------------------------------------------------
typedef std::pair<std::string, std::string> HttpHeader;
@@ -24,6 +38,10 @@ public:
return headers_.size();
}
bool empty() const {
return headers_.empty();
}
const std::vector<HttpHeader>& data() const {
return headers_;
}
@@ -131,6 +149,95 @@ private:
bool valid_ = false;
};
// -----------------------------------------------------------------------------
// Form data part.
class FormPart {
public:
FormPart() = default;
explicit FormPart(const std::string& name, const Path& path,
const std::string& mime_type = "");
FormPart(std::string&& data, const std::string& file_name,
const std::string& mime_type = "");
#if WEBCC_DEFAULT_MOVE_COPY_ASSIGN
FormPart(FormPart&&) = default;
FormPart& operator=(FormPart&&) = default;
#else
FormPart(FormPart&& rhs)
: name_(std::move(rhs.name_)),
file_name_(std::move(rhs.file_name_)),
mime_type_(std::move(rhs.mime_type_)),
data_(std::move(rhs.data_)) {
}
FormPart& operator=(FormPart&& rhs) {
if (&rhs != this) {
name_ = std::move(rhs.name_);
file_name_ = std::move(rhs.file_name_);
mime_type_ = std::move(rhs.mime_type_);
data_ = std::move(rhs.data_);
}
return *this;
}
#endif // WEBCC_DEFAULT_MOVE_COPY_ASSIGN
const std::string& name() const {
return name_;
}
void set_name(const std::string& name) {
name_ = name;
}
const std::string& file_name() const {
return file_name_;
}
void set_file_name(const std::string& file_name) {
file_name_ = file_name;
}
const std::string& mime_type() const {
return mime_type_;
}
const std::string& data() const {
return data_;
}
void AppendData(const std::string& data) {
data_.append(data);
}
void AppendData(const char* data, std::size_t size) {
data_.append(data, size);
}
void Prepare(Payload& payload);
private:
std::string name_;
// E.g., example.jpg
// TODO: Unicode
std::string file_name_;
// E.g., image/jpeg
std::string mime_type_;
HttpHeaders headers_;
// Binary file data.
std::string data_;
};
} // namespace webcc
#endif // WEBCC_COMMON_H_