commit 0c5b0d228818660278203b5bfe642d2bc5c5caf9
parent b0700162c4627501de91a3046990f4913bf04d57
Author: Joris Vink <joris@coders.se>
Date: Mon, 4 Aug 2014 21:06:02 +0200
Add an example that parses JSON via yajl
Diffstat:
4 files changed, 99 insertions(+), 0 deletions(-)
diff --git a/examples/json_yajl/.gitignore b/examples/json_yajl/.gitignore
@@ -0,0 +1,5 @@
+*.o
+.objs
+json_yajl.so
+assets.h
+cert
diff --git a/examples/json_yajl/README.md b/examples/json_yajl/README.md
@@ -0,0 +1,16 @@
+This example demonstrates how you can use external libs in your application.
+
+In this case we link against yajl (Yet Another JSON library) in order to
+parse a JSON string that was POSTed to the server.
+
+Run:
+```
+ env KORE_LDFLAGS="-lyajl" kore 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: Hello world.
diff --git a/examples/json_yajl/conf/json_yajl.conf b/examples/json_yajl/conf/json_yajl.conf
@@ -0,0 +1,13 @@
+# Placeholder configuration
+
+bind 127.0.0.1 8888
+pidfile kore.pid
+ssl_no_compression
+load ./json_yajl.so
+
+domain 127.0.0.1 {
+ certfile cert/server.crt
+ certkey cert/server.key
+
+ static / page
+}
diff --git a/examples/json_yajl/src/json_yajl.c b/examples/json_yajl/src/json_yajl.c
@@ -0,0 +1,65 @@
+#include <kore/kore.h>
+#include <kore/http.h>
+
+#include <yajl/yajl_tree.h>
+
+int page(struct http_request *);
+
+int
+page(struct http_request *req)
+{
+ struct kore_buf *buf;
+ char *body;
+ yajl_val node, v;
+ char eb[1024];
+ const char *path[] = { "foo", "bar", NULL };
+
+ /* We only allow POST methods. */
+ if (req->method != HTTP_METHOD_POST) {
+ http_response(req, 400, NULL, 0);
+ return (KORE_RESULT_OK);
+ }
+
+ /*
+ * Grab the entire body we received as text (NUL-terminated).
+ * Note: this can return NULL and the result MUST be freed.
+ */
+ if ((body = http_post_data_text(req)) == NULL) {
+ http_response(req, 400, NULL, 0);
+ return (KORE_RESULT_OK);
+ }
+
+ /* Parse the body via yajl now. */
+ node = yajl_tree_parse(body, eb, sizeof(eb));
+ if (node == NULL) {
+ if (strlen(eb)) {
+ kore_log(LOG_NOTICE, "parse error: %s", eb);
+ } else {
+ kore_log(LOG_NOTICE, "parse error: unknown");
+ }
+
+ kore_mem_free(body);
+ http_response(req, 400, NULL, 0);
+ return (KORE_RESULT_OK);
+ }
+
+ buf = kore_buf_create(128);
+
+ /* Attempt to grab foo.bar from the JSON tree. */
+ v = yajl_tree_get(node, path, yajl_t_string);
+ if (v == NULL) {
+ kore_buf_appendf(buf, "no such path: foo.bar\n");
+ } else {
+ kore_buf_appendf(buf, "foo.bar = '%s'\n", YAJL_GET_STRING(v));
+ }
+
+ /* Release the JSON tree now. */
+ yajl_tree_free(node);
+ kore_mem_free(body);
+
+ /* Respond to the client. */
+ http_response(req, 200, buf->data, buf->offset);
+ kore_buf_free(buf);
+
+ return (KORE_RESULT_OK);
+}