1 | #ifndef CPR_BODY_H |
2 | #define CPR_BODY_H |
3 | |
4 | #include <exception> |
5 | #include <fstream> |
6 | #include <initializer_list> |
7 | #include <string> |
8 | #include <vector> |
9 | |
10 | #include "cpr/buffer.h" |
11 | #include "cpr/cprtypes.h" |
12 | #include "cpr/file.h" |
13 | |
14 | namespace cpr { |
15 | |
16 | class Body : public StringHolder<Body> { |
17 | public: |
18 | Body() = default; |
19 | // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) |
20 | Body(std::string body) : StringHolder<Body>(std::move(body)) {} |
21 | // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) |
22 | Body(std::string_view body) : StringHolder<Body>(body) {} |
23 | // NOLINTNEXTLINE(google-explicit-constructor, hicpp-explicit-conversions) |
24 | Body(const char* body) : StringHolder<Body>(body) {} |
25 | Body(const char* str, size_t len) : StringHolder<Body>(str, len) {} |
26 | Body(const std::initializer_list<std::string> args) : StringHolder<Body>(args) {} |
27 | // NOLINTNEXTLINE(google-explicit-constructor, cppcoreguidelines-pro-type-reinterpret-cast) |
28 | Body(const Buffer& buffer) : StringHolder<Body>(reinterpret_cast<const char*>(buffer.data), static_cast<size_t>(buffer.datalen)) {} |
29 | // NOLINTNEXTLINE(google-explicit-constructor) |
30 | Body(const File& file) { |
31 | std::ifstream is(file.filepath, std::ifstream::binary); |
32 | if (!is) { |
33 | throw std::invalid_argument("Can't open the file for HTTP request body!" ); |
34 | } |
35 | |
36 | is.seekg(0, std::ios::end); |
37 | const std::streampos length = is.tellg(); |
38 | is.seekg(0, std::ios::beg); |
39 | std::string buffer; |
40 | buffer.resize(n: static_cast<size_t>(length)); |
41 | is.read(s: buffer.data(), n: length); |
42 | str_ = std::move(buffer); |
43 | } |
44 | Body(const Body& other) = default; |
45 | Body(Body&& old) noexcept = default; |
46 | ~Body() override = default; |
47 | |
48 | Body& operator=(Body&& old) noexcept = default; |
49 | Body& operator=(const Body& other) = default; |
50 | }; |
51 | |
52 | } // namespace cpr |
53 | |
54 | #endif |
55 | |