Skip to content

Instantly share code, notes, and snippets.

@oz
Created April 10, 2012 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oz/2355431 to your computer and use it in GitHub Desktop.
Save oz/2355431 to your computer and use it in GitHub Desktop.
Tofu example to speak JSON
/**
* 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;
}
@francois2metz
Copy link

The Content-type should be application/json :)

@nono
Copy link

nono commented Apr 11, 2012

I think this example leaks memory. Shouldn't it free the obj pointer in hello?

@oz
Copy link
Author

oz commented Apr 11, 2012

@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 a text/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 than free 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. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment