Add native JSON parser example

This commit is contained in:
Joris Vink 2019-10-20 23:40:08 +02:00
parent e94cc2f3a8
commit dc55a48d87
5 changed files with 105 additions and 0 deletions

5
examples/json/.gitignore vendored Executable file
View File

@ -0,0 +1,5 @@
*.o
.objs
json.so
assets.h
cert

13
examples/json/README.md Normal file
View File

@ -0,0 +1,13 @@
Native Kore JSON parser example.
Run:
```
$ kodev run
```
Test:
```
$ curl -i -k -d '{"foo":{"bar": "Hello world"}}' https://127.0.0.1:8888
```
The result should echo back the foo.bar JSON path value if it is a JSON string.

View File

@ -0,0 +1,18 @@
# json build config
# You can switch flavors using: kodev flavor [newflavor]
# The cflags below are shared between flavors
cflags=-Wall -Wmissing-declarations -Wshadow
cflags=-Wstrict-prototypes -Wmissing-prototypes
cflags=-Wpointer-arith -Wcast-qual -Wsign-compare
dev {
# These cflags are added to the shared ones when
# you build the "dev" flavor.
cflags=-g
}
#prod {
# You can specify additional CFLAGS here which are only
# included if you build with the "prod" flavor.
#}

19
examples/json/conf/json.conf Executable file
View File

@ -0,0 +1,19 @@
# Placeholder configuration
server tls {
bind 127.0.0.1 8888
}
load ./json.so
tls_dhparam dh2048.pem
domain 127.0.0.1 {
attach tls
certfile cert/server.pem
certkey cert/key.pem
static / page
restrict / post
}

50
examples/json/src/json.c Executable file
View File

@ -0,0 +1,50 @@
/*
* Copyright (c) 2019 Joris Vink <joris@coders.se>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <kore/kore.h>
#include <kore/http.h>
int page(struct http_request *);
int
page(struct http_request *req)
{
struct kore_buf buf;
struct kore_json json;
struct kore_json_item *item;
kore_buf_init(&buf, 128);
kore_json_init(&json, req->http_body->data, req->http_body->length);
if (!kore_json_parse(&json)) {
kore_buf_appendf(&buf, "%s\n", kore_json_strerror(&json));
} else {
if ((item = kore_json_string(&json, "foo/bar")) != NULL) {
kore_buf_appendf(&buf,
"foo.bar = '%s'\n", item->data.string);
} else {
kore_buf_appendf(&buf, "%s\n",
kore_json_strerror(&json));
}
}
http_response(req, 200, buf.data, buf.offset);
kore_buf_cleanup(&buf);
kore_json_cleanup(&json);
return (KORE_RESULT_OK);
}