Created
May 16, 2016 10:06
-
-
Save byronmejia/76e6fbfef11e96f92c44afd23477634f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <kore/kore.h> | |
| #include <kore/http.h> | |
| #include <kore/pgsql.h> | |
| #include <string.h> | |
| #include "device.h" | |
| /* Page handler entry point (see config) */ | |
| int json_devices(struct http_request *req){ | |
| struct kore_pgsql sql; | |
| char *name; | |
| int json_len = 0; | |
| int rows, i, j, len; | |
| char *json = NULL; | |
| req->status = HTTP_STATUS_INTERNAL_ERROR; | |
| if (!kore_pgsql_query_init(&sql, NULL, "db", KORE_PGSQL_SYNC)) { | |
| kore_pgsql_logerror(&sql); | |
| goto out; | |
| } | |
| if (!kore_pgsql_query(&sql, "SELECT * FROM devices")) { | |
| kore_pgsql_logerror(&sql); | |
| goto out; | |
| } | |
| rows = kore_pgsql_ntuples(&sql); | |
| for (i = 0; i < rows; i++) { | |
| name = kore_pgsql_getvalue(&sql, i, 0); | |
| len = strlen(name); | |
| kore_log(LOG_NOTICE, "name: '%s'", name); | |
| kore_log(LOG_NOTICE, "length: %i", len); | |
| json_len += len; | |
| } | |
| // Add the open and close square bracket, for output format | |
| json_len += 2; | |
| // Add the comma separators | |
| json_len += (rows-1); | |
| kore_log(LOG_NOTICE, "total_row: %i", rows); | |
| kore_log(LOG_NOTICE, "total_len: %i", json_len); | |
| // Allocate that total size to the char array | |
| json = (char *) malloc(sizeof(char) * json_len); | |
| // Repeat for loop to safely add to this mess of an array | |
| int count = 0; | |
| json[count] = '['; | |
| count++; | |
| for (i = 0; i < rows; i++) { | |
| name = kore_pgsql_getvalue(&sql, i, 0); | |
| len = strlen(name); | |
| json[count] = '"'; | |
| count++; | |
| for(j = 0; j < len; j++){ | |
| json[count] = name[j]; | |
| count++; | |
| } | |
| json[count] = '"'; | |
| count++; | |
| if(i < rows-1){ | |
| json[count] = ','; | |
| count++; | |
| } | |
| } | |
| json[count] = ']'; | |
| count++; | |
| json[count] = '\0'; | |
| // DEBUG | |
| kore_log(LOG_NOTICE, "OUTPUT: %s", json); | |
| kore_log(LOG_NOTICE, "OUTPUT: %i", strlen(json)); | |
| kore_log(LOG_NOTICE, "OUTPUT: %i", json_len); | |
| /* All good. */ | |
| req->status = HTTP_STATUS_OK; | |
| out: | |
| http_response(req, req->status, json, strlen(json)); | |
| /* Don't forget to cleanup the kore_pgsql data structure. */ | |
| kore_pgsql_cleanup(&sql); | |
| return (KORE_RESULT_OK); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment