File: rest_test.cpp

package info (click to toggle)
glaze 6.5.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,948 kB
  • sloc: cpp: 121,839; sh: 99; ansic: 26; makefile: 13
file content (353 lines) | stat: -rw-r--r-- 12,127 bytes parent folder | download
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// Glaze Library
// For the license information refer to glaze.hpp

#include <fstream>
#include <iostream>

#include "glaze/glaze.hpp"
#include "glaze/net/http_server.hpp"
#include "ut/ut.hpp"

using namespace ut;

struct User
{
   int id{};
   std::string name{};
   std::string email{};
};

struct ErrorResponse
{
   std::string error{};
};

int main()
{
   // Create a server
   glz::http_server server;

   // Mock database
   std::unordered_map<int, User> users = {{1, {1, "John Doe", "john@example.com"}},
                                          {2, {2, "Jane Smith", "jane@example.com"}}};
   int next_id = 3;

   // Set up routes for API
   server.get("/api/users", [&](const glz::request& /*req*/, glz::response& res) {
      std::vector<User> user_list;
      for (const auto& [id, user] : users) {
         user_list.push_back(user);
      }
      res.json(user_list);
   });

   server.get("/api/users/:id", [&](const glz::request& req, glz::response& res) {
      try {
         // Get the id from the path parameters
         int id = std::stoi(req.params.at("id"));

         // Find the user
         auto it = users.find(id);
         if (it != users.end()) {
            res.json(it->second);
         }
         else {
            res.status(404).json(ErrorResponse{"User not found"});
         }
      }
      catch (const std::exception& e) {
         res.status(400).json(ErrorResponse{"Invalid user ID"});
      }
   });

   server.post("/api/users", [&](const glz::request& req, glz::response& res) {
      // Parse JSON request body
      auto result = glz::read_json<User>(req.body);
      if (!result) {
         res.status(400).json(ErrorResponse{glz::format_error(result, req.body)});
         return;
      }

      User user = result.value();
      user.id = next_id++;

      // Add to database
      users[user.id] = user;

      // Return the created user
      res.status(201).json(user);
   });

   // Serve the frontend files
   server.get("/", [](const glz::request& /*req*/, glz::response& res) {
      // Inline HTML for simplicity (in a real app, you would read from a file)
      std::string html = R"(
      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Glaze REST API Demo</title>
      <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
            color: #333;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background-color: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            color: #2c3e50;
            margin-top: 0;
        }
        h2 {
            color: #3498db;
            margin-top: 30px;
        }
        .card {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 15px;
            transition: transform 0.2s;
        }
        .card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"],
        input[type="email"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        button:hover {
            background-color: #2980b9;
        }
        .user-id {
            font-weight: bold;
            color: #7f8c8d;
        }
        .error {
            color: #e74c3c;
            margin-top: 10px;
        }
        .success {
            color: #27ae60;
            margin-top: 10px;
        }
        #loading {
            text-align: center;
            margin: 20px 0;
            display: none;
        }
        .hidden {
            display: none;
        }
      </style>
      </head>
      <body>
      <div class="container">
        <h1>Glaze REST API Demo</h1>
        <p>A simple demonstration of the Glaze REST API functionality.</p>
        
        <h2>All Users</h2>
        <div id="usersList"></div>
        <div id="loading">Loading...</div>
        
        <h2>Get User by ID</h2>
        <div class="form-group">
            <label for="userId">User ID:</label>
            <input type="text" id="userId" placeholder="Enter user ID">
        </div>
        <button id="getUser">Get User</button>
        <div id="userResult" class="hidden card"></div>
        <div id="userError" class="error hidden"></div>
        
        <h2>Add New User</h2>
        <div class="form-group">
            <label for="userName">Name:</label>
            <input type="text" id="userName" placeholder="Enter name">
        </div>
        <div class="form-group">
            <label for="userEmail">Email:</label>
            <input type="email" id="userEmail" placeholder="Enter email">
        </div>
        <button id="addUser">Add User</button>
        <div id="addSuccess" class="success hidden">User added successfully!</div>
        <div id="addError" class="error hidden"></div>
      </div>
      
      <script>
        // Fetch all users
        async function fetchUsers() {
            document.getElementById('loading').style.display = 'block';
            document.getElementById('usersList').innerHTML = '';
            
            try {
                const response = await fetch('/api/users');
                const users = await response.json();
                
                document.getElementById('loading').style.display = 'none';
                
                if (users.length === 0) {
                    document.getElementById('usersList').innerHTML = '<p>No users found</p>';
                    return;
                }
                
                users.forEach(user => {
                    const userCard = document.createElement('div');
                    userCard.className = 'card';
                    userCard.innerHTML = `
                        <p><span class="user-id">ID: ${user.id}</span></p>
                        <p><strong>Name:</strong> ${user.name}</p>
                        <p><strong>Email:</strong> ${user.email}</p>
                    `;
                    document.getElementById('usersList').appendChild(userCard);
                });
            } catch (error) {
                document.getElementById('loading').style.display = 'none';
                document.getElementById('usersList').innerHTML = `<p class="error">Error loading users: ${error.message}</p>`;
            }
        }
        
        // Get user by ID
        document.getElementById('getUser').addEventListener('click', async () => {
            const userId = document.getElementById('userId').value;
            if (!userId) {
                document.getElementById('userError').textContent = 'Please enter a user ID';
                document.getElementById('userError').classList.remove('hidden');
                document.getElementById('userResult').classList.add('hidden');
                return;
            }
            
            try {
                const response = await fetch(`/api/users/${userId}`);
                const data = await response.json();
                
                if (response.status === 404) {
                    document.getElementById('userError').textContent = data.error || 'User not found';
                    document.getElementById('userError').classList.remove('hidden');
                    document.getElementById('userResult').classList.add('hidden');
                    return;
                }
                
                if (response.status === 400) {
                    document.getElementById('userError').textContent = data.error || 'Invalid request';
                    document.getElementById('userError').classList.remove('hidden');
                    document.getElementById('userResult').classList.add('hidden');
                    return;
                }
                
                document.getElementById('userError').classList.add('hidden');
                document.getElementById('userResult').classList.remove('hidden');
                document.getElementById('userResult').innerHTML = `
                    <p><span class="user-id">ID: ${data.id}</span></p>
                    <p><strong>Name:</strong> ${data.name}</p>
                    <p><strong>Email:</strong> ${data.email}</p>
                `;
            } catch (error) {
                document.getElementById('userError').textContent = `Error: ${error.message}`;
                document.getElementById('userError').classList.remove('hidden');
                document.getElementById('userResult').classList.add('hidden');
            }
        });
        
        // Add new user
        document.getElementById('addUser').addEventListener('click', async () => {
            const name = document.getElementById('userName').value;
            const email = document.getElementById('userEmail').value;
            
            if (!name || !email) {
                document.getElementById('addError').textContent = 'Please fill in all fields';
                document.getElementById('addError').classList.remove('hidden');
                document.getElementById('addSuccess').classList.add('hidden');
                return;
            }
            
            try {
                const response = await fetch('/api/users', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ name, email })
                });
                
                const data = await response.json();
                
                if (response.status !== 201) {
                    document.getElementById('addError').textContent = data.error || 'Failed to add user';
                    document.getElementById('addError').classList.remove('hidden');
                    document.getElementById('addSuccess').classList.add('hidden');
                    return;
                }
                
                document.getElementById('addError').classList.add('hidden');
                document.getElementById('addSuccess').classList.remove('hidden');
                document.getElementById('userName').value = '';
                document.getElementById('userEmail').value = '';
                
                // Refresh the users list
                fetchUsers();
            } catch (error) {
                document.getElementById('addError').textContent = `Error: ${error.message}`;
                document.getElementById('addError').classList.remove('hidden');
                document.getElementById('addSuccess').classList.add('hidden');
            }
        });
        
        // Initialize
        document.addEventListener('DOMContentLoaded', () => {
            fetchUsers();
        });
      </script>
      </body>
      </html>
      )";

      res.content_type("text/html").body(html);
   });

   // Start the server
   server.bind("127.0.0.1", 8080).with_signals(); // Enable built-in signal handling

   std::cout << "Server listening on http://127.0.0.1:8080" << std::endl;
   std::cout << "Press Ctrl+C to gracefully shut down the server" << std::endl;

   server.start();

   // Wait for shutdown signal (blocks until server stops)
   server.wait_for_signal();

   std::cout << "Server shut down successfully" << std::endl;

   return 0;
}