Skip to content

Commit

Permalink
feat: router && logger
Browse files Browse the repository at this point in the history
  • Loading branch information
PedroFnseca committed Aug 29, 2023
1 parent 5a0d25d commit 25303ac
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 3 deletions.
Binary file added bin/handler.o
Binary file not shown.
Binary file modified bin/main
Binary file not shown.
Binary file modified bin/main.o
Binary file not shown.
25 changes: 25 additions & 0 deletions src/handler.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#include <stdio.h>
#include <string.h>
#include <microhttpd.h>
#include "logger.h"

enum MHD_Result default_handler(void *cls, struct MHD_Connection *connection, const char *url,
const char *method, const char *version, const char *upload_data,
size_t *upload_data_size, void **con_cls) {
struct MHD_Response *response;
char *url_str = (char *)url;
char *method_str = (char *)method;
int ret;

log_api(url_str, method_str);

response = MHD_create_response_from_buffer(strlen(url_str), (void *)url_str, MHD_RESPMEM_PERSISTENT);

if (!response)
return MHD_NO;

ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
MHD_destroy_response(response);

return ret;
}
20 changes: 20 additions & 0 deletions src/logger.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#include <stdio.h>
#include <string.h>

void log_api(const char *url, const char *method, const char *status_code) {
char *color;

if (strcmp(method, "GET") == 0) {
color = "\033[0;32m";
} else if (strcmp(method, "POST") == 0) {
color = "\033[0;33m";
} else if (strcmp(method, "PUT") == 0) {
color = "\033[0;34m";
} else if (strcmp(method, "DELETE") == 0) {
color = "\033[0;35m";
} else {
color = "\033[0;36m";
}

printf("%s[%s] %s -> %s\n", color, method, url);
}
23 changes: 20 additions & 3 deletions src/main.c
Original file line number Diff line number Diff line change
@@ -1,7 +1,24 @@
#include <stdio.h>
#include <string.h>
#include <microhttpd.h>
#include "handler.h"

int main(int argc, char *argv[]) {
printf("Hello, Wolrd!\n");
return 0;
#define PORT 8080
#define color_green "\033[0;32m"

int main() {
printf("%sStart server on port %d\n", color_green, PORT);

struct MHD_Daemon *daemon;

daemon = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION, PORT, NULL, NULL,
&default_handler, NULL, MHD_OPTION_END);
if (!daemon)
return 1;

getchar();

MHD_stop_daemon(daemon);

return 0;
}

0 comments on commit 25303ac

Please sign in to comment.