-
Notifications
You must be signed in to change notification settings - Fork 253
Url handler
The url handler is the only included handler in the core of libonion. It is nontheless the most useful and complete.
It helps to map regular expressions to handlers, in a fashion similar to django urls. It also has some extra helpers to help user to avoid direct contact with the handler API. This simplifies most web application developments.
URL handlers can be created in two ways: directly from the onion object, effectively setting it as root, or as a url object and setting it as any other handler. The first is done with onion_root_url(onion *onion);
and the second with onion_url_new();
.
onion_root_url
will return the onion_url *
object, or NULL if there is already a root handler and its not a url handler.
Then the user may use any of the following functions:
-
onion_url_add(onion_url *url, const char *regexp, void *f);
Just sets a function to call, with no arguments, when the regexp matches. The function has to fit anyway theonion_handler_handler
signature:onion_connection_status f(void *privdata, onion_request *req, onion_response *res);
, but privdata will always be NULL. -
onion_url_add_with_data(onion_url *url, const char *regexp, void *f, void *privdata, void *privdatafree);
Sets the function to call when regexp matches, with the given data. The privdata will be freed when needed using privdatafree function. -
onion_url_add_handler(onion_url *url, const char *regexp, onion_handler *handler);
The handler will be called when the regexp matches. -
onion_url_add_static(onion_url *url, const char *regexp, const char *text, int httpcode);
The static data will be returned, with the httpcode as indicated.
Also useful are onion_url_free
and onion_url_to_handler
. This last function converts the onion_url *
to onion_handler *
, to be used as a normal handler.
There are no means by the moment to pass the function the matched substrings, a quite useful feature of Django's urls, but some will be added in the future.
Normal use would be like:
#include <onion/onion.h>
int hello(void *p, onion_request *req, onion_response *res){
onion_response_set_length(res, 11);
onion_response_write(res,"Hello world",11);
return OCS_PROCESSED;
}
int main(int argc, char **argv){
onion *o=onion_new(O_THREADED);
onion_url *urls=onion_root_url(o);
onion_url_add_static(urls, "^static$", "Hello static world", HTTP_OK);
onion_url_add(urls, "^$", hello);
onion_listen(o);
onion_free(o);
return 0;
}