src/HTTPServer.cpp
author František Kučera <franta-hg@frantovo.cz>
Thu, 07 Apr 2022 23:04:12 +0200
branchv_0
changeset 2 4b05b16b97e6
parent 1 23c516259cc5
child 3 1184f3de5533
permissions -rw-r--r--
configurable TCP listener port + RequestHandler interface

/**
 * 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/>.
 */

#include <microhttpd.h>
#include <stdexcept>

#include "HTTPServer.h"

namespace relpipe {
namespace tr {
namespace httpd {

class HTTPServer::HTTPServerImpl {
public:
	MHD_Daemon* mhd = nullptr;
	std::shared_ptr<RequestHandler> requestHandler;
};

void HTTPServer::setRequestHandler(std::shared_ptr<RequestHandler> handler) {
	impl->requestHandler = handler;
}

HTTPServer* HTTPServer::create(HTTPServer::Options options) {
	HTTPServer::HTTPServerImpl* impl = new HTTPServer::HTTPServerImpl();

	void* acceptCallbackData = nullptr;
	MHD_AcceptPolicyCallback acceptCallback = [](void* cls, const struct sockaddr* addr, socklen_t addrlen) {
		return MHD_YES;
	};

	void* accessCallbackData = nullptr;
	MHD_AccessHandlerCallback accessCallback = [](void* cls, struct MHD_Connection* connection, const char* url, const char* method, const char* version, const char* upload_data, size_t* upload_data_size, void** con_cls) {
		static const char html[] = "<p>Hello, <b>relational</b> world!</p>";
		struct MHD_Response* response = MHD_create_response_from_buffer(sizeof (html), (void*) html, MHD_RESPMEM_PERSISTENT);
		MHD_queue_response(connection, 200, response);
		MHD_destroy_response(response);
		return MHD_YES;
	};


	impl->mhd = MHD_start_daemon(MHD_USE_INTERNAL_POLLING_THREAD,
			options.tcpPort,
			acceptCallback, acceptCallbackData,
			accessCallback, accessCallbackData,
			MHD_OPTION_THREAD_POOL_SIZE, 10,
			MHD_OPTION_CONNECTION_TIMEOUT, 60,
			MHD_OPTION_END);


	if (impl->mhd) return new HTTPServer(impl);
	else throw std::logic_error("Unable to start MHD.");
}

HTTPServer::~HTTPServer() {
	MHD_stop_daemon(impl->mhd);
	delete impl;
}


}
}
}