75 lines
1.8 KiB
C++
75 lines
1.8 KiB
C++
|
|
#pragma once
|
|
|
|
#if !defined(MIJIN_NET_HTTP_HPP_INCLUDED)
|
|
#define MIJIN_NET_HTTP_HPP_INCLUDED 1
|
|
|
|
#include <memory>
|
|
#include <string>
|
|
#include <map>
|
|
#include "./socket.hpp"
|
|
#include "./url.hpp"
|
|
#include "../container/boxed_object.hpp"
|
|
#include "../io/stream.hpp"
|
|
|
|
namespace mijin
|
|
{
|
|
struct HTTPVersion
|
|
{
|
|
unsigned major;
|
|
unsigned minor;
|
|
};
|
|
|
|
struct HTTPRequest
|
|
{
|
|
HTTPVersion version = {1, 1};
|
|
std::string address;
|
|
std::string method = "GET";
|
|
std::multimap<std::string, std::string> headers;
|
|
std::string body;
|
|
};
|
|
|
|
struct HTTPResponse
|
|
{
|
|
HTTPVersion version;
|
|
unsigned status;
|
|
std::string statusMessage;
|
|
std::multimap<std::string, std::string> headers;
|
|
std::string content;
|
|
};
|
|
|
|
class HTTPStream
|
|
{
|
|
private:
|
|
Stream* base_;
|
|
public:
|
|
HTTPStream(Stream& base) noexcept : base_(&base)
|
|
{
|
|
MIJIN_ASSERT(base_ != nullptr, "Invalid parameter for base.");
|
|
}
|
|
Task<StreamResult<HTTPResponse>> c_request(HTTPRequest request) noexcept;
|
|
private:
|
|
Task<StreamError> c_writeRequest(const HTTPRequest& request) noexcept;
|
|
Task<StreamResult<HTTPResponse>> c_readResponse() noexcept;
|
|
};
|
|
|
|
class HTTPClient
|
|
{
|
|
private:
|
|
std::unique_ptr<Socket> socket_;
|
|
mijin::BoxedObject<HTTPStream> stream_;
|
|
ip_address_t lastIP_;
|
|
std::uint16_t lastPort_ = 0;
|
|
bool lastWasHttps_ = false;
|
|
public:
|
|
~HTTPClient() noexcept { disconnect(); }
|
|
Task<StreamResult<HTTPResponse>> c_request(ip_address_t address, std::uint16_t port, bool https, HTTPRequest request) noexcept;
|
|
Task<StreamResult<HTTPResponse>> c_request(const URL& url, HTTPRequest request = {}) noexcept;
|
|
void disconnect() noexcept;
|
|
private:
|
|
StreamError createSocket(ip_address_t address, std::uint16_t port, bool https) noexcept;
|
|
};
|
|
}
|
|
|
|
#endif // !defined(MIJIN_NET_HTTP_HPP_INCLUDED)
|