yaze 0.3.2
Link to the Past ROM Editor
 
Loading...
Searching...
No Matches
http_server.cc
Go to the documentation of this file.
2
4#include "util/log.h"
5
6// Include httplib implementation in one file or just use the header if
7// header-only usually cpp-httplib is header only, so just including is enough.
8// However, we need to be careful about multiple definitions if we include it in
9// multiple .cc files without precautions? cpp-httplib is header only.
10#include "httplib.h"
11
12namespace yaze {
13namespace cli {
14namespace api {
15
16HttpServer::HttpServer() : server_(std::make_unique<httplib::Server>()) {}
17
21
22absl::Status HttpServer::Start(int port) {
23 if (is_running_) {
24 return absl::AlreadyExistsError("Server is already running");
25 }
26
27 if (!server_->is_valid()) {
28 return absl::InternalError("HttpServer is not valid");
29 }
30
32
33 // Start server in a separate thread
34 is_running_ = true;
35
36 // Capture server pointer to avoid race conditions if 'this' is destroyed
37 // (though HttpServer shouldn't be)
38 server_thread_ = std::make_unique<std::thread>([this, port]() {
39 LOG_INFO("HttpServer", "Starting API server on port %d", port);
40 bool ret = server_->listen("0.0.0.0", port);
41 if (!ret) {
42 LOG_ERROR("HttpServer",
43 "Failed to listen on port %d. Port might be in use.", port);
44 }
45 is_running_ = false;
46 });
47
48 return absl::OkStatus();
49}
50
52 if (is_running_) {
53 LOG_INFO("HttpServer", "Stopping API server...");
54 server_->stop();
55 if (server_thread_ && server_thread_->joinable()) {
56 server_thread_->join();
57 }
58 is_running_ = false;
59 LOG_INFO("HttpServer", "API server stopped");
60 }
61}
62
64 return is_running_;
65}
66
68 server_->Get("/api/v1/health", HandleHealth);
69 server_->Get("/api/v1/models", HandleListModels);
70
71 // Handle CORS options for all routes?
72 // For now, we set CORS headers in individual handlers or via a middleware if
73 // httplib supported it easily.
74}
75
76} // namespace api
77} // namespace cli
78} // namespace yaze
std::unique_ptr< httplib::Server > server_
Definition http_server.h:38
absl::Status Start(int port)
std::unique_ptr< std::thread > server_thread_
Definition http_server.h:39
std::atomic< bool > is_running_
Definition http_server.h:40
#define LOG_ERROR(category, format,...)
Definition log.h:109
#define LOG_INFO(category, format,...)
Definition log.h:105
void HandleListModels(const httplib::Request &req, httplib::Response &res)
void HandleHealth(const httplib::Request &req, httplib::Response &res)