Restserver update

This commit is contained in:
2017-09-14 22:01:00 +02:00
parent 9e1807fcb0
commit d75632c61d
7 changed files with 110 additions and 226 deletions

View File

@@ -1,3 +1,97 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define U_DISABLE_CURL
#define U_DISABLE_WEBSOCKET
#include <ulfius.h>
#define PORT 8080
#define PREFIX "/test"
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!");
return U_CALLBACK_CONTINUE;
}
char * print_map(const struct _u_map * map) {
char * line, * to_return = NULL;
const char **keys, * value;
int len, i;
if (map != NULL) {
keys = u_map_enum_keys(map);
for (i=0; keys[i] != NULL; i++) {
value = u_map_get(map, keys[i]);
len = snprintf(NULL, 0, "key is %s, value is %s", keys[i], value);
line = o_malloc((len+1)*sizeof(char));
snprintf(line, (len+1), "key is %s, value is %s", keys[i], value);
if (to_return != NULL) {
len = strlen(to_return) + strlen(line) + 1;
to_return = o_realloc(to_return, (len+1)*sizeof(char));
if (strlen(to_return) > 0) {
strcat(to_return, "\n");
}
} else {
to_return = o_malloc((strlen(line) + 1)*sizeof(char));
to_return[0] = 0;
}
strcat(to_return, line);
o_free(line);
}
return to_return;
} else {
return NULL;
}
}
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;
}
int main(void) {
struct _u_instance instance;
// 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);
}
instance.max_post_body_size = 1024;
// 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);
// Start the framework
if (ulfius_start_framework(&instance) == U_OK) {
printf("Start framework on port %d\n", instance.port);
// Wait for the user to press <enter> on the console to quit the application
getchar();
} else {
fprintf(stderr, "Error starting framework\n");
}
printf("End framework\n");
ulfius_stop_framework(&instance);
ulfius_clean_instance(&instance);
return 0;
}