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
|
#include <stdio.h>
#include <string.h>
#include <dlfcn.h>
#include "microhttpd.h"
typedef char*(*endpoint)(struct MHD_Connection*);
enum MHD_Result process_connection(void *dylib, struct MHD_Connection *connection, const char *url,
const char *method, const char *version, const char *upload_data,
size_t *upload_data_size, void **req_cls)
{
printf("\nurl: %s\nmethod:%s\nversion:%s\nupload_data:%s\nsize:%zu\n",
url, method, version, upload_data, *upload_data_size);
/* Load function with the name of the url from shared library */
endpoint handler = dlsym(dylib, url);
struct MHD_Response *res; int status;
if (handler != NULL) {
fprintf(stderr, "Accessed at url\t%s\n", url);
char* response = handler(connection);
res = MHD_create_response_from_buffer(strlen(response), response, MHD_RESPMEM_MUST_FREE);
status = MHD_HTTP_OK;
} else {
fprintf(stderr, "Failed to access at url\t%s\n", url);
const char* error = "<html><body>Error 404: Page does not exist</body></html>";
res = MHD_create_response_from_buffer(strlen(error), (void*)error, MHD_RESPMEM_PERSISTENT);
status = MHD_HTTP_NOT_FOUND;
}
MHD_queue_response(connection, status, res);
MHD_destroy_response(res);
return MHD_YES;
}
int main(){
void* dylib = dlopen("./endpoints.so", RTLD_NOW);
if (!dylib) {
fprintf(stderr, "Could not open dynamic library: %s\n", dlerror());
return 1;
}
struct MHD_Daemon *daemon = MHD_start_daemon(MHD_USE_POLL | MHD_USE_INTERNAL_POLLING_THREAD, 8080, NULL, NULL, process_connection, dylib, MHD_OPTION_END);
if (daemon == NULL) {
perror("daemon");
fprintf(stderr, "could not initialize daemon\n");
return 1;
}
getchar();
MHD_stop_daemon(daemon);
return 0;
}
|