Skip to content

Instantly share code, notes, and snippets.

@babelouest
Created October 15, 2023 21:59
Show Gist options
  • Save babelouest/685e16e26047e9d47c4ec699695817ec to your computer and use it in GitHub Desktop.
Save babelouest/685e16e26047e9d47c4ec699695817ec to your computer and use it in GitHub Desktop.
POC for ulfius issue #269
/**
* issue-269.c
* https://github.com/babelouest/ulfius/issues/269
* to compile with gcc, run the following command
* gcc -o issue-269 issue-269.c -lulfius
*/
#include <stdio.h>
#include <ulfius.h>
#define PORT 8080
struct _handlers {
pthread_mutex_t global_handler_close_lock;
pthread_cond_t global_handler_close_cond;
};
/**
* Callback function for the web application on /helloworld url call
*/
int callback_hello_world (const struct _u_request * request, struct _u_response * response, void * user_data) {
sleep(5);
ulfius_set_string_body_response(response, 200, "Hello World!");
return U_CALLBACK_CONTINUE;
}
int callback_shutdown (const struct _u_request * request, struct _u_response * response, void * user_data) {
struct _handlers * handlers = (struct _handlers *)user_data;
ulfius_set_string_body_response(response, 200, "Shtting down");
pthread_mutex_lock(&handlers->global_handler_close_lock);
pthread_cond_signal(&handlers->global_handler_close_cond);
pthread_mutex_unlock(&handlers->global_handler_close_lock);
return U_CALLBACK_CONTINUE;
}
/**
* main function
*/
int main(void) {
struct _u_instance instance;
struct _handlers handlers;
if (pthread_mutex_init(&handlers.global_handler_close_lock, NULL) ||
pthread_cond_init(&handlers.global_handler_close_cond, NULL)) {
fprintf(stderr, "Error initializing global_handler_close_lock or global_handler_close_cond\n");
}
// Initialize instance with the port number
if (ulfius_init_instance(&instance, PORT, NULL, NULL) != U_OK) {
fprintf(stderr, "Error ulfius_init_instance, abort\n");
return(1);
}
// Endpoint list declaration
ulfius_add_endpoint_by_val(&instance, "GET", "/helloworld", NULL, 0, &callback_hello_world, NULL);
ulfius_add_endpoint_by_val(&instance, "GET", "/shutdown", NULL, 0, &callback_shutdown, &handlers);
// Start the framework
if (ulfius_start_framework(&instance) == U_OK) {
printf("Start framework on port %d\n", instance.port);
pthread_mutex_lock(&handlers.global_handler_close_lock);
pthread_cond_wait(&handlers.global_handler_close_cond, &handlers.global_handler_close_lock);
pthread_mutex_unlock(&handlers.global_handler_close_lock);
} else {
fprintf(stderr, "Error starting framework\n");
}
printf("End framework\n");
ulfius_stop_framework(&instance);
ulfius_clean_instance(&instance);
if (pthread_mutex_destroy(&handlers.global_handler_close_lock) ||
pthread_cond_destroy(&handlers.global_handler_close_cond)) {
fprintf(stderr, "Error destroying global_handler_close_lock or global_handler_close_cond\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment