kore

An easy to use, scalable and secure web application framework for writing web APIs in C.
Commits | Files | Refs | README | LICENSE | git clone https://git.kore.io/kore.git

json.c (1811B)



      1 /*
      2  * Copyright (c) 2019 Joris Vink <joris@coders.se>
      3  *
      4  * Permission to use, copy, modify, and distribute this software for any
      5  * purpose with or without fee is hereby granted, provided that the above
      6  * copyright notice and this permission notice appear in all copies.
      7  *
      8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     15  */
     16 
     17 #include <kore/kore.h>
     18 #include <kore/http.h>
     19 
     20 int		page(struct http_request *);
     21 
     22 int
     23 page(struct http_request *req)
     24 {
     25 	struct kore_buf		buf;
     26 	struct kore_json	json;
     27 	struct kore_json_item	*item;
     28 
     29 	kore_buf_init(&buf, 128);
     30 	kore_json_init(&json, req->http_body->data, req->http_body->length);
     31 
     32 	if (!kore_json_parse(&json)) {
     33 		kore_buf_appendf(&buf, "%s\n", kore_json_strerror());
     34 	} else {
     35 		item = kore_json_find_string(json.root, "foo/bar");
     36 		if (item != NULL) {
     37 			kore_buf_appendf(&buf,
     38 			    "foo.bar = '%s'\n", item->data.string);
     39 		} else {
     40 			kore_buf_appendf(&buf, "foo.bar %s\n",
     41 			    kore_json_strerror());
     42 		}
     43 
     44 		item = kore_json_find_integer_u64(json.root, "foo/integer");
     45 		if (item != NULL) {
     46 			kore_buf_appendf(&buf,
     47 			    "foo.integer = '%" PRIu64 "'\n", item->data.u64);
     48 		} else {
     49 			kore_buf_appendf(&buf, "foo.integer %s\n",
     50 			    kore_json_strerror());
     51 		}
     52 	}
     53 
     54 	http_response(req, 200, buf.data, buf.offset);
     55 
     56 	kore_buf_cleanup(&buf);
     57 	kore_json_cleanup(&json);
     58 
     59 	return (KORE_RESULT_OK);
     60 }