-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
447 lines (358 loc) · 11.8 KB
/
Copy pathmain.c
File metadata and controls
447 lines (358 loc) · 11.8 KB
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <libpq-fe.h>
#include <cjson/cJSON.h>
#define PORT 8080
#define BUFFER_SIZE 8192
#define MAX_CONNECTIONS 100
// Estrutura para configuração do banco
typedef struct {
char *host;
char *port;
char *dbname;
char *user;
char *password;
} db_config_t;
// Estrutura para requisição HTTP
typedef struct {
char *method;
char *path;
char *body;
int content_length;
} http_request_t;
// Estrutura para resposta HTTP
typedef struct {
int status;
char *content_type;
char *body;
} http_response_t;
// Variáveis globais (Pike Style: simplicidade)
static PGconn *db_conn = NULL;
static db_config_t db_config = {
.host = "localhost",
.port = "5432",
.dbname = "apidb",
.user = "apiuser",
.password = "apipass"
};
// Função para inicializar conexão com PostgreSQL
int db_init(void) {
char conn_str[512];
snprintf(conn_str, sizeof(conn_str),
"host=%s port=%s dbname=%s user=%s password=%s",
db_config.host, db_config.port, db_config.dbname,
db_config.user, db_config.password);
db_conn = PQconnectdb(conn_str);
if (PQstatus(db_conn) != CONNECTION_OK) {
fprintf(stderr, "Erro na conexão: %s", PQerrorMessage(db_conn));
PQfinish(db_conn);
return -1;
}
printf("Conectado ao PostgreSQL\n");
return 0;
}
// Função para fechar conexão
void db_close(void) {
if (db_conn) {
PQfinish(db_conn);
db_conn = NULL;
}
}
// Função para executar query e retornar JSON
char* db_query_json(const char *query) {
PGresult *res;
cJSON *json_array, *json_obj;
char *json_string;
int rows, cols, i, j;
if (!db_conn) return NULL;
res = PQexec(db_conn, query);
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
fprintf(stderr, "Query falhou: %s", PQerrorMessage(db_conn));
PQclear(res);
return NULL;
}
rows = PQntuples(res);
cols = PQnfields(res);
json_array = cJSON_CreateArray();
for (i = 0; i < rows; i++) {
json_obj = cJSON_CreateObject();
for (j = 0; j < cols; j++) {
char *field_name = PQfname(res, j);
char *field_value = PQgetvalue(res, i, j);
cJSON_AddStringToObject(json_obj, field_name, field_value);
}
cJSON_AddItemToArray(json_array, json_obj);
}
json_string = cJSON_Print(json_array);
cJSON_Delete(json_array);
PQclear(res);
return json_string;
}
// Função para executar INSERT/UPDATE/DELETE
int db_execute(const char *query) {
PGresult *res;
if (!db_conn) return -1;
res = PQexec(db_conn, query);
if (PQresultStatus(res) != PGRES_COMMAND_OK) {
fprintf(stderr, "Comando falhou: %s", PQerrorMessage(db_conn));
PQclear(res);
return -1;
}
PQclear(res);
return 0;
}
// Função para parsear requisição HTTP simples
http_request_t* parse_request(const char *raw_request) {
http_request_t *req = malloc(sizeof(http_request_t));
char *line, *token, *request_copy;
char *saveptr;
if (!req) return NULL;
memset(req, 0, sizeof(http_request_t));
request_copy = strdup(raw_request);
// Parse da primeira linha (METHOD PATH HTTP/1.1)
line = strtok_r(request_copy, "\r\n", &saveptr);
if (line) {
char *method = strtok(line, " ");
char *path = strtok(NULL, " ");
if (method) req->method = strdup(method);
if (path) req->path = strdup(path);
}
// Parse dos headers
while ((line = strtok_r(NULL, "\r\n", &saveptr)) != NULL) {
if (strlen(line) == 0) break; // Headers terminam com linha vazia
if (strncmp(line, "Content-Length:", 15) == 0) {
req->content_length = atoi(line + 16);
}
}
// Parse do body (se houver)
if (req->content_length > 0) {
char *body_start = strstr(raw_request, "\r\n\r\n");
if (body_start) {
body_start += 4;
req->body = strndup(body_start, req->content_length);
}
}
free(request_copy);
return req;
}
// Função para criar resposta HTTP
char* create_response(http_response_t *resp) {
char *response = malloc(BUFFER_SIZE);
int len;
if (!response) return NULL;
len = snprintf(response, BUFFER_SIZE,
"HTTP/1.1 %d %s\r\n"
"Content-Type: %s\r\n"
"Content-Length: %ld\r\n"
"Connection: close\r\n"
"\r\n"
"%s",
resp->status,
resp->status == 200 ? "OK" : "Error",
resp->content_type ? resp->content_type : "text/plain",
resp->body ? strlen(resp->body) : 0,
resp->body ? resp->body : "");
return response;
}
// Handler para GET /users
char* handle_get_users(void) {
return db_query_json("SELECT id, name, email FROM users ORDER BY id");
}
char* handle_del_users(const char *json_body) {
cJSON *json = cJSON_Parse(json_body);
char query[512];
char *name, *email;
int result;
if (!json) return -1;
cJSON *name_item = cJSON_GetObjectItem(json, "name");
cJSON *email_item = cJSON_GetObjectItem(json, "email");
if (!name_item || !email_item) {
cJSON_Delete(json);
return -1;
}
name = name_item->valuestring;
email = email_item->valuestring;
snprintf(query, sizeof(query),
"DELETE FROM users WHERE name = '%s' and email = '%s'",
name, email);
result = db_execute(query);
cJSON_Delete(json);
return result;
}
// Handler para POST /users
int handle_post_users(const char *json_body) {
cJSON *json = cJSON_Parse(json_body);
char query[512];
char *name, *email;
int result;
if (!json) return -1;
cJSON *name_item = cJSON_GetObjectItem(json, "name");
cJSON *email_item = cJSON_GetObjectItem(json, "email");
if (!name_item || !email_item) {
cJSON_Delete(json);
return -1;
}
name = name_item->valuestring;
email = email_item->valuestring;
snprintf(query, sizeof(query),
"INSERT INTO users (name, email) VALUES ('%s', '%s')",
name, email);
result = db_execute(query);
cJSON_Delete(json);
return result;
}
// Roteador principal
void handle_request(int client_socket, http_request_t *req) {
http_response_t resp = {0};
char *response_str;
// GET /users
if (strcmp(req->method, "GET") == 0 && strcmp(req->path, "/users") == 0) {
char *json_data = handle_get_users();
if (json_data) {
resp.status = 200;
resp.content_type = "application/json";
resp.body = json_data;
} else {
resp.status = 500;
resp.content_type = "text/plain";
resp.body = "Erro interno";
}
}
// POST /users
else if (strcmp(req->method, "POST") == 0 && strcmp(req->path, "/users") == 0) {
if (req->body && handle_post_users(req->body) == 0) {
resp.status = 201;
resp.content_type = "application/json";
resp.body = "{\"message\": \"Usuario criado\"}";
} else {
resp.status = 400;
resp.content_type = "application/json";
resp.body = "{\"error\": \"Dados invalidos\"}";
}
}
// DELETE /users
else if (strcmp(req->method, "DELETE") == 0 && strcmp(req->path, "/users") == 0) {
if (req->body && handle_del_users(req->body) == 0) {
resp.status = 204;
resp.content_type = "application/json";
resp.body = "{\"message\": \"Usuario excluido\"}";
} else {
resp.status = 400;
resp.content_type = "application/json";
resp.body = "{\"error\": \"Dados invalidos\"}";
}
}
// GET /health
else if (strcmp(req->method, "GET") == 0 && strcmp(req->path, "/health") == 0) {
resp.status = 200;
resp.content_type = "application/json";
resp.body = "{\"status\": \"OK\", \"database\": \"connected\"}";
}
// 404 Not Found
else {
resp.status = 404;
resp.content_type = "application/json";
resp.body = "{\"error\": \"Endpoint nao encontrado\"}";
}
response_str = create_response(&resp);
if (response_str) {
send(client_socket, response_str, strlen(response_str), 0);
free(response_str);
}
// Liberar memória do JSON (se foi alocado dinamicamente)
if (resp.status == 200 && strcmp(req->path, "/users") == 0) {
free(resp.body);
}
}
// Função para liberar requisição
void free_request(http_request_t *req) {
if (!req) return;
free(req->method);
free(req->path);
free(req->body);
free(req);
}
// Função principal do servidor
int start_server(void) {
int server_fd, client_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE];
// Criar socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
return -1;
}
// Configurar reutilização de endereço
int opt = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
perror("setsockopt");
return -1;
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// Bind
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
return -1;
}
// Listen
if (listen(server_fd, MAX_CONNECTIONS) < 0) {
perror("listen");
return -1;
}
printf("Servidor rodando na porta %d\n", PORT);
// Loop principal
while (1) {
client_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen);
if (client_socket < 0) {
perror("accept");
continue;
}
// Ler requisição
ssize_t bytes_read = read(client_socket, buffer, BUFFER_SIZE - 1);
if (bytes_read > 0) {
buffer[bytes_read] = '\0';
http_request_t *req = parse_request(buffer);
if (req) {
handle_request(client_socket, req);
free_request(req);
}
}
close(client_socket);
}
close(server_fd);
return 0;
}
int main(int argc, char *argv[]) {
// Inicializar banco de dados
if (db_init() != 0) {
fprintf(stderr, "Falha ao conectar no banco\n");
return 1;
}
// Criar tabela se não existir
const char *create_table =
"CREATE TABLE IF NOT EXISTS users ("
"id SERIAL PRIMARY KEY,"
"name VARCHAR(100) NOT NULL,"
"email VARCHAR(100) UNIQUE NOT NULL,"
"created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP"
")";
if (db_execute(create_table) != 0) {
fprintf(stderr, "Falha ao criar tabela\n");
db_close();
return 1;
}
printf("Tabela 'users' criada/verificada\n");
// Iniciar servidor
int result = start_server();
// Cleanup
db_close();
return result;
}