src/HTTPClient.h
author František Kučera <franta-hg@frantovo.cz>
Thu, 24 Mar 2022 02:02:48 +0100
branchv_0
changeset 20 cad9f6d421ee
parent 11 6b913e82f52a
permissions -rw-r--r--
support header filtering also by request ID pattern, not only URL pattern

/**
 * Relational pipes
 * Copyright © 2022 František Kučera (Frantovo.cz, GlobalCode.info)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#pragma once

#include <string>
#include <vector>
#include <stdexcept>

#include <relpipe/common/type/typedefs.h>


namespace relpipe {
namespace tr {
namespace http {

/**
 * Simple synchronous client for the HTTP and HTTPS protocol.
 * Is not thread-safe – must not be called from multiple threads simultaneously.
 */
class HTTPClient {
private:
	class HTTPClientImpl;
	HTTPClientImpl* impl;

	HTTPClient(HTTPClientImpl* impl) : impl(impl) {
	}


public:

	enum class Method {
		GET,
		HEAD,
		POST,
		PUT,
		DELETE,
		// CONNECT,
		// OPTIONS,
		// TRACE,
		PATCH,
	};

	struct Request {
		Method method = Method::GET;
		std::string url;
		std::vector<std::string> headers;
		std::string body;
	};

	struct Response {
		int responseCode = 0;
		std::vector<std::string> headers;
		std::string body;
	};

	class Exception : public std::runtime_error {
	private:
		std::string details;
	public:

		Exception(const std::string& message, const std::string& details) : runtime_error(message), details(details) {
		}

		Exception(const std::string& message) : runtime_error(message) {
		}

		Exception(const char* message) : runtime_error(message) {
		}

		std::string getDetails() const {
			return details;
		}
		
		std::string getFullMessage() const {
			return std::string(what()) + ": " + details;
		}
	};

	virtual ~HTTPClient();
	HTTPClient(const HTTPClient&) = delete;
	HTTPClient& operator=(const HTTPClient&) = delete;

	static HTTPClient* open();

	const Response exchange(const Request& request);

};

}
}
}