multipart.hpp
1 #ifndef XXHR_MULTIPART_H
2 #define XXHR_MULTIPART_H
3 
4 #include <cstdint>
5 #include <initializer_list>
6 #include <string>
7 #include <type_traits>
8 #include <vector>
9 
10 #include "defines.hpp"
11 
12 namespace xxhr {
13 
17 struct File {
18  template <typename StringType>
19  explicit File(StringType&& filepath)
20  : filepath{XXHR_FWD(filepath)} {}
21  std::string filepath;
22 };
23 
27 struct Buffer {
28  typedef const unsigned char* data_t;
29 
30  template <typename Iterator, typename StringType>
31  explicit Buffer(Iterator begin, Iterator end, StringType&& filename)
32  : data{reinterpret_cast<data_t>(&(*begin))},
33  datalen{static_cast<unsigned long>(std::distance(begin, end))},
34  filename{XXHR_FWD(filename)} {
35  is_random_access_iterator(begin, end);
36  static_assert(sizeof(*begin) == 1, "only byte buffers can be used");
37  }
38 
39  template <typename Iterator>
40  typename std::enable_if<std::is_same<typename std::iterator_traits<Iterator>::iterator_category,
41  std::random_access_iterator_tag>::value>::type
42  is_random_access_iterator(Iterator begin, Iterator end) {}
43 
44  data_t data;
45  unsigned long datalen;
46  std::string filename;
47 };
48 
52 struct Part {
53  Part(const std::string& name, const std::string& value, const std::string& content_type = {})
54  : name{name}, value{value}, content_type{content_type}, is_file{false},
55  is_buffer{false} {}
56  Part(const std::string& name, const std::int32_t& value, const std::string& content_type = {})
57  : name{name}, value{std::to_string(value)}, content_type{content_type}, is_file{false},
58  is_buffer{false} {}
59  Part(const std::string& name, const File& file, const std::string& content_type = {})
60  : name{name}, value{file.filepath}, content_type{content_type}, is_file{true},
61  is_buffer{false} {}
62  Part(const std::string& name, const Buffer& buffer, const std::string& content_type = {})
63  : name{name}, value{buffer.filename}, content_type{content_type}, data{buffer.data},
64  datalen{buffer.datalen}, is_file{false}, is_buffer{true} {}
65 
66  std::string name;
67  std::string value;
68  std::string content_type;
69  Buffer::data_t data;
70  unsigned long datalen;
71  bool is_file;
72  bool is_buffer;
73 };
74 
83 class Multipart {
84  public:
85  Multipart(const std::initializer_list<Part>& parts) : parts{parts} {}
86 
87  std::vector<Part> parts;
88 };
89 
90 } // namespace xxhr
91 
92 #endif
xxhr::File
Local file path to send in an xxhr::Multipart.
Definition: multipart.hpp:17
xxhr::Multipart
Allows to specify HTTP Multipart requests. Useful in xxhr::POST context to perform data upload.
Definition: multipart.hpp:83
xxhr::Part
Buffer or File part of an xxhr::Multipart transfer.
Definition: multipart.hpp:52
xxhr::Buffer
In memory buffer to send in an xxhr::Multipart.
Definition: multipart.hpp:27
xxhr
main library namespace
Definition: api.hpp:20