Bug fixing

This commit is contained in:
Your Name
2025-05-25 14:48:05 +12:00
parent d849aa73f4
commit 3cffb6cd94
5 changed files with 98 additions and 1 deletions

View File

@@ -123,6 +123,16 @@ void Server::stop() {
}
void Server::setup_routes() {
// Add CORS preflight handler for all routes
server_.Options(".*", [this](const httplib::Request& req, httplib::Response& res) {
handle_cors_preflight(req, res);
});
// Add CORS headers to all responses
server_.set_post_routing_handler([this](const httplib::Request& req, httplib::Response& res) {
add_cors_headers(req, res);
});
const std::string welcome_page = "<html><body><h1>simple_object_storage Template Registry</h1></body></html>";
// Welcome page
server_.Get("/", [welcome_page](const httplib::Request&, httplib::Response& res) {
@@ -180,6 +190,58 @@ void Server::setup_routes() {
});
}
void Server::handle_cors_preflight(const httplib::Request& req, httplib::Response& res) {
add_cors_headers(req, res);
res.status = 204; // No content
}
void Server::add_cors_headers(const httplib::Request& req, httplib::Response& res) {
// Get the origin from the request
std::string origin = req.get_header_value("Origin");
// If no origin header, no CORS headers needed
if (origin.empty()) {
return;
}
// Check if origin is allowed
bool origin_allowed = false;
if (config_.allowed_origins.empty() ||
std::find(config_.allowed_origins.begin(), config_.allowed_origins.end(), "*") != config_.allowed_origins.end()) {
origin_allowed = true;
} else {
origin_allowed = std::find(config_.allowed_origins.begin(), config_.allowed_origins.end(), origin) != config_.allowed_origins.end();
}
if (origin_allowed) {
res.set_header("Access-Control-Allow-Origin", origin);
// Add other CORS headers
std::string methods = join(config_.allowed_methods, ", ");
res.set_header("Access-Control-Allow-Methods", methods);
std::string headers = join(config_.allowed_headers, ", ");
res.set_header("Access-Control-Allow-Headers", headers);
if (config_.allow_credentials) {
res.set_header("Access-Control-Allow-Credentials", "true");
}
// Add max age for preflight requests
res.set_header("Access-Control-Max-Age", "86400"); // 24 hours
}
}
std::string Server::join(const std::vector<std::string>& strings, const std::string& delimiter) {
if (strings.empty()) return "";
std::string result = strings[0];
for (size_t i = 1; i < strings.size(); ++i) {
result += delimiter + strings[i];
}
return result;
}
void Server::handle_get_object(const httplib::Request& req, httplib::Response& res) {
const auto& key = req.matches[1].str();
std::string hash_str = key;