view include/core/http.h @ 390:2d3e10319112

http: optimize HTTP request thread we don't need a mutex at all, in fact all we need is an atomic boolean to signify whether the thread is cancelled. curl options are now for the most part handled by a separate function to keep them in sync between non-threaded and threaded implementations
author Paper <paper@tflc.us>
date Fri, 07 Nov 2025 07:08:57 -0500
parents 1e5d922fe82b
children 963047512d34
line wrap: on
line source

#ifndef MINORI_CORE_HTTP_H_
#define MINORI_CORE_HTTP_H_

#include <QByteArray>
#include <QThread>

#include <mutex>
#include <string>
#include <vector>
#include <atomic>

namespace HTTP {

/* calls libcurl to encode/decode */
std::string UrlEncode(const std::string &data);
std::string UrlDecode(const std::string &data);

std::string EncodeParamsList(std::string base, const std::map<std::string, std::string> &params);

enum class Type {
	Get,
	Post,
	Patch
};

QByteArray Request(const std::string &url, const std::vector<std::string> &headers = {}, const std::string &data = "",
                   Type type = Type::Get);

class RequestThread final : public QThread {
	Q_OBJECT

public:
	RequestThread(Type type = Type::Get, QObject *parent = nullptr);
	RequestThread(const std::string &url, const std::vector<std::string> &headers = {}, const std::string &data = "",
	              Type type = Type::Get, QObject *parent = nullptr);
	~RequestThread();

	void SetUrl(const std::string &url);
	void SetHeaders(const std::vector<std::string> &headers);
	void SetData(const std::string &data);
	void SetType(Type type);

	void Stop();

signals:
	void ReceivedData(const QByteArray &ba);

protected:
	void run() override;
	static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userdata);

	std::string url_;
	std::string data_;
	std::vector<std::string> headers_;
	Type type_;
	void *curl_;

	/* these are passed to the write callback */
	QByteArray array_;
	std::atomic<bool> cancelled_ = false;
};

} // namespace HTTP

#endif // MINORI_CORE_HTTP_H_