1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
|
// Glaze REST Demo Server
#include <filesystem>
#include <fstream>
#include <iostream>
#include "glaze/glaze.hpp"
#include "glaze/net/http_server.hpp"
#include "glaze/rpc/registry.hpp"
struct User
{
int id{};
std::string name{};
std::string email{};
std::string avatar{};
};
struct UserIdRequest
{
int id{};
};
struct UserCreateRequest
{
std::string name{};
std::string email{};
std::string avatar{};
};
struct UserUpdateRequest
{
int id{};
std::string name{};
std::string email{};
std::string avatar{};
};
struct DeleteResponse
{
bool success{};
std::string message{};
};
struct PostCreateRequest
{
std::string title{};
std::string body{};
std::string author{};
};
struct Post
{
int id{};
std::string title{};
std::string body{};
std::string author{};
std::string createdAt{};
};
// User service with CRUD operations
struct UserService
{
std::unordered_map<int, User> users = {{1, {1, "Alice Johnson", "alice@example.com", "👩💼"}},
{2, {2, "Bob Smith", "bob@example.com", "👨💻"}},
{3, {3, "Carol Davis", "carol@example.com", "👩🎨"}}};
int next_id = 4;
// Get all users
std::vector<User> getAllUsers()
{
std::vector<User> user_list;
for (const auto& [id, user] : users) {
user_list.push_back(user);
}
return user_list;
}
// Get user by ID
User getUserById(const UserIdRequest& request)
{
auto it = users.find(request.id);
if (it != users.end()) {
return it->second;
}
return User{}; // Return empty user if not found
}
// Create a new user
User createUser(const UserCreateRequest& request)
{
User user;
user.id = next_id++;
user.name = request.name;
user.email = request.email;
user.avatar = request.avatar.empty() ? "👤" : request.avatar;
users[user.id] = user;
return user;
}
// Update existing user
User updateUser(const UserUpdateRequest& request)
{
auto it = users.find(request.id);
if (it != users.end()) {
it->second.name = request.name;
it->second.email = request.email;
if (!request.avatar.empty()) {
it->second.avatar = request.avatar;
}
return it->second;
}
return User{}; // Return empty user if not found
}
// Delete user
DeleteResponse deleteUser(const UserIdRequest& request)
{
auto it = users.find(request.id);
if (it != users.end()) {
users.erase(it);
return {true, "User deleted successfully"};
}
return {false, "User not found"};
}
};
// Simple blog post service for more complex demo
struct PostService
{
std::unordered_map<int, Post> posts = {
{1,
{1, "Welcome to Glaze", "This is a demo of Mithril with a Glaze C++ backend.", "Alice Johnson",
"2025-05-27T10:00:00Z"}},
{2,
{2, "Building REST APIs", "Learn how to build REST APIs with Glaze library.", "Bob Smith",
"2025-05-27T11:00:00Z"}}};
int next_id = 3;
std::vector<Post> getAllPosts()
{
std::vector<Post> post_list;
for (const auto& [id, post] : posts) {
post_list.push_back(post);
}
return post_list;
}
Post createPost(const PostCreateRequest& request)
{
Post post;
post.id = next_id++;
post.title = request.title;
post.body = request.body;
post.author = request.author;
post.createdAt = std::to_string(std::time(nullptr)); // Simple timestamp
posts[post.id] = post;
return post;
}
};
// Glaze metadata for reflection
template <>
struct glz::meta<UserService>
{
using T = UserService;
static constexpr auto value =
object(&T::getAllUsers, &T::getUserById, &T::createUser, &T::updateUser, &T::deleteUser);
};
template <>
struct glz::meta<PostService>
{
using T = PostService;
static constexpr auto value = object(&T::getAllPosts, &T::createPost);
};
std::string read_file(const std::string& path)
{
std::string full_path = std::string{SOURCE_DIR} + "/" + path;
std::ifstream file(full_path, std::ios::ate | std::ios::binary);
if (!file.is_open()) {
std::cerr << "Failed to open " << full_path << ", current directory: " << std::filesystem::current_path().string()
<< "\n";
return "";
}
// Get the file size from the current position (since we used std::ios::ate)
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::string buffer;
buffer.resize(size);
if (file.read(buffer.data(), size)) {
return buffer;
}
return "";
}
// Helper function to check if file exists
bool file_exists(const std::string& path)
{
std::string full_path = std::string{SOURCE_DIR} + "/" + path;
return std::filesystem::exists(full_path);
}
// Helper function to get MIME type
std::string get_mime_type(const std::string& path)
{
std::filesystem::path p(path);
std::string ext = p.extension().string();
if (ext == ".html") return "text/html";
if (ext == ".js") return "application/javascript";
if (ext == ".css") return "text/css";
if (ext == ".json") return "application/json";
if (ext == ".png") return "image/png";
if (ext == ".jpg" || ext == ".jpeg") return "image/jpeg";
if (ext == ".gif") return "image/gif";
if (ext == ".svg") return "image/svg+xml";
return "text/plain";
}
int main()
{
glz::http_server server;
// Create service instances
UserService userService;
PostService postService;
// Create REST registry
glz::registry<glz::opts{}, glz::REST> registry;
// Register services
registry.on(userService);
registry.on(postService);
// OPTION 1: Enable CORS with default settings (allow all origins - good for development)
server.enable_cors();
// OPTION 2: Enable CORS with custom configuration
/*
glz::cors_config cors_config;
cors_config.allowed_origins = {"http://localhost:3000", "https://myapp.com"};
cors_config.allowed_methods = {"GET", "POST", "PUT", "DELETE"};
cors_config.allowed_headers = {"Content-Type", "Authorization", "X-API-Key"};
cors_config.allow_credentials = true;
cors_config.max_age = 3600; // 1 hour
server.enable_cors(cors_config);
*/
// OPTION 3: Enable CORS for specific origins (good for production)
/*
server.enable_cors({
"https://myapp.com",
"https://api.myapp.com"
}, true); // allow credentials
*/
// Mount API endpoints
server.mount("/api", registry.endpoints);
// Serve static files
server.get("/", [](const glz::request& /*req*/, glz::response& res) {
std::string html = read_file("index.html");
if (html.empty()) {
res.status(404).body("index.html not found");
}
else {
res.content_type("text/html").body(html);
}
});
// Example of a custom endpoint that returns CORS headers
server.get("/test-cors", [](const glz::request& req, glz::response& res) {
// The CORS middleware will automatically add the appropriate headers
res.json({{"message", "CORS test endpoint"},
{"origin", req.headers.count("origin") ? req.headers.at("origin") : "none"},
{"method", glz::to_string(req.method)}});
});
// Start the server
server.bind("127.0.0.1", 8080).with_signals(); // Enable signal handling for graceful shutdown
std::cout << "Glaze Demo Server running on http://127.0.0.1:8080\n";
std::cout << "Press Ctrl+C to gracefully shut down the server\n\n";
server.start();
// Wait for shutdown signal (blocks until server stops)
server.wait_for_signal();
std::cout << "Server shut down successfully\n";
return 0;
}
|