Created
April 10, 2012 23:07
-
-
Save oz/2355431 to your computer and use it in GitHub Desktop.
Tofu example to speak JSON
This file contains 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
/** | |
* A simple Tofu example to speak JSON. | |
* | |
* Compile: | |
* If you make-installed Tofu, skip the -I/-L flags. If not, export | |
* TOFU=/wherever/you/git-cloned/and/built/Tofu | |
* | |
* $ gcc hello.c -ltofu -ljansson -I$TOFU/include -L$TOFU/src/.libs -o hello | |
* | |
* Run: | |
* $ ./hello | |
* Server started at http://0.0.0.0:8080/ | |
* | |
* Check: | |
* $ curl http://localhost:8080/hello/world | |
* {"hello": "world"} | |
* $ | |
* | |
*/ | |
#include <stdio.h> | |
#include <jansson.h> | |
#include <tofu.h> | |
#define LISTEN_ADDR "0.0.0.0" | |
#define LISTEN_PORT "8080" | |
tofu_rep_t *hello(tofu_req_t *req, void *argp) { | |
tofu_rep_t *rep = tofu_rep_init(); | |
char *reply = NULL; | |
char *param = tofu_param(req, "name"); | |
json_t *obj = json_object(); | |
json_object_set(obj, "hello", json_string(param)); | |
reply = json_dumps(obj, JSON_ENSURE_ASCII); | |
tofu_head(rep, "Content-Type", "text/plain"); | |
tofu_write(rep, reply); | |
tofu_write(rep, "\n"); | |
free(reply); | |
return rep; | |
} | |
int main(int ac, char ** av) { | |
char *opts[] = { LISTEN_ADDR, LISTEN_PORT }; | |
tofu_ctx_t *ctx = tofu_ctx_init(TOFU_EVHTTP, opts); | |
tofu_handle_with(ctx, GET, "/hello/:name", hello, 0x0); | |
fprintf(stdout, "Server started at http://%s:%s/\n", | |
LISTEN_ADDR, LISTEN_PORT); | |
tofu_loop(ctx); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@francois2metz You're absolutely right! if you plan to use JSON, that's the way to go. In this example however, I simply copied the behavior of the latest Go app @nono built. It's just more obvious here since the Content-Type is in plain sight... Plus for people like my mom, who are not using
curl
, having atext/plain
header helps testing in a browser too. :p@nono Yup. However, Jansson's lib is a little trickier than that, and one would rather play with
json_decref
thanfree
to let the lib do its own GC once the refcount drops to zero. I did not check thoroughly, but I'm quite sure Tofu's HEAD on master leaks memory by itself too (hey there is a PoC-only warning in their README afterall).Thanks for your remarks. :)