From b5f64016b727c36261d73ef6eedc2b67fcd33fb8 Mon Sep 17 00:00:00 2001 From: structix Date: Sat, 16 Sep 2017 16:40:25 +0200 Subject: [PATCH] Got the ulfius rest server working --- RestServer/main.c | 56 ++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 46 insertions(+), 10 deletions(-) diff --git a/RestServer/main.c b/RestServer/main.c index ca54714..f237741 100644 --- a/RestServer/main.c +++ b/RestServer/main.c @@ -12,8 +12,8 @@ #define U_DISABLE_WEBSOCKET #include -#define PORT 8080 -#define PREFIX "/test" +#define PORT 1337 +#define PREFIX "/abshum" int callback_welcome (const struct _u_request * request, struct _u_response * response, void * user_data) { ulfius_set_string_body_response(response, 200, "Welcome to the HumidityPi rest service!"); @@ -21,6 +21,8 @@ int callback_welcome (const struct _u_request * request, struct _u_response * re } + + char * print_map(const struct _u_map * map) { char * line, * to_return = NULL; const char **keys, * value; @@ -51,15 +53,49 @@ char * print_map(const struct _u_map * map) { } } -int callback_post_test (const struct _u_request * request, struct _u_response * response, void * user_data) { - char * post_params = print_map(request->map_post_body); - char * response_body = msprintf("Hello World!\n%s", post_params); - ulfius_set_string_body_response(response, 200, response_body); - o_free(response_body); - o_free(post_params); - return U_CALLBACK_CONTINUE; +char * read_file(const char * filename) { + char * buffer = NULL; + long length; + FILE * f = fopen (filename, "rb"); + if (filename != NULL) { + + if (f) { + fseek (f, 0, SEEK_END); + length = ftell (f); + fseek (f, 0, SEEK_SET); + buffer = o_malloc (length + 1); + if (buffer) { + fread (buffer, 1, length, f); + } + buffer[length] = '\0'; + fclose (f); + } + return buffer; + } else { + return NULL; + } } +int callback_all_test_foo (const struct _u_request * request, struct _u_response * response, void * user_data) { + //char * url_params = print_map(request->map_url); + //char * response_body = msprintf("parameters from the url are \n%s\n\n", + //url_params); + int i; + float temphum[2]; + const char **keys; + keys = u_map_enum_keys(request->map_url); + + for (i = 0; i < 2; i++) { + temphum[i] = atoi(u_map_get(request->map_url, keys[i])); + } + char *response_body = msprintf("Temp: %f, Hum: %f",temphum[0], temphum[1]); + + ulfius_set_string_body_response(response, 200, response_body); + //o_free(url_params); + return U_CALLBACK_CONTINUE; +} + + int main(void) { @@ -76,7 +112,7 @@ int main(void) { // Endpoint list declaration ulfius_add_endpoint_by_val(&instance, "GET", "/welcome", NULL, 0, &callback_welcome, NULL); - ulfius_add_endpoint_by_val(&instance, "POST", "/test", NULL, 0, &callback_post_test, NULL); + ulfius_add_endpoint_by_val(&instance, "GET", PREFIX, "/:temp/:hum", 0, &callback_all_test_foo, NULL); // Start the framework if (ulfius_start_framework(&instance) == U_OK) {