static void handle_sum_call(struct ns_connection *nc, struct http_message *hm) { char n1[100], n2[100]; /* Get form variables */ ns_get_http_var(&hm->body, "n1", n1, sizeof(n1)); ns_get_http_var(&hm->body, "n2", n2, sizeof(n2)); ns_printf(nc, "%s", "HTTP/1.0 200 OK\n\n"); ns_printf(nc, "{ \"result\": %lf }", strtod(n1, NULL) + strtod(n2, NULL)); }
static void handle_sum_call(struct ns_connection *nc, struct http_message *hm) { char n1[100], n2[100]; double result; /* Get form variables */ ns_get_http_var(&hm->body, "n1", n1, sizeof(n1)); ns_get_http_var(&hm->body, "n2", n2, sizeof(n2)); /* Send headers */ ns_printf(nc, "%s", "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"); /* Compute the result and send it back as a JSON object */ result = strtod(n1, NULL) + strtod(n2, NULL); ns_printf_http_chunk(nc, "{ \"result\": %lf }", result); ns_send_http_chunk(nc, "", 0); /* Send empty chunk, the end of response */ }
static void op_set(struct ns_connection *nc, const struct http_message *hm, const struct ns_str *key, void *db) { sqlite3_stmt *stmt = NULL; char value[200]; const struct ns_str *body = hm->query_string.len > 0 ? &hm->query_string : &hm->body; ns_get_http_var(body, "value", value, sizeof(value)); if (sqlite3_prepare_v2(db, "INSERT OR REPLACE INTO kv VALUES (?, ?);", -1, &stmt, NULL) == SQLITE_OK) { sqlite3_bind_text(stmt, 1, key->p, key->len, SQLITE_STATIC); sqlite3_bind_text(stmt, 2, value, strlen(value), SQLITE_STATIC); sqlite3_step(stmt); sqlite3_finalize(stmt); } ns_printf(nc, "%s", "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); }
static const char *test_get_http_var(void) { char buf[256]; struct ns_str body; body.p = "key1=value1&key2=value2&key3=value%203&key4=value+4"; body.len = strlen(body.p); ASSERT(ns_get_http_var(&body, "key1", buf, sizeof(buf)) > 0); ASSERT(strcmp(buf, "value1") == 0); ASSERT(ns_get_http_var(&body, "KEY1", buf, sizeof(buf)) > 0); ASSERT(strcmp(buf, "value1") == 0); ASSERT(ns_get_http_var(&body, "key2", buf, sizeof(buf)) > 0); ASSERT(strcmp(buf, "value2") == 0); ASSERT(ns_get_http_var(&body, "key3", buf, sizeof(buf)) > 0); ASSERT(strcmp(buf, "value 3") == 0); ASSERT(ns_get_http_var(&body, "key4", buf, sizeof(buf)) > 0); ASSERT(strcmp(buf, "value 4") == 0); ASSERT(ns_get_http_var(&body, "key", NULL, sizeof(buf)) == -2); ASSERT(ns_get_http_var(&body, "key", buf, 0) == -2); ASSERT(ns_get_http_var(&body, NULL, buf, sizeof(buf)) == -1); return NULL; }