lnm/example/routing.c

71 lines
1.9 KiB
C

#include <unistd.h>
#include "lnm/http/req.h"
#include "lnm/log.h"
#include "lnm/loop.h"
#include "lnm/http/loop.h"
lnm_err ctx_init(void **c_ctx, void *gctx) {
*c_ctx = NULL;
return lnm_err_ok;
}
void ctx_reset(void *c_ctx) {}
void ctx_free(void *c_ctx) {}
lnm_http_step_err print_step(lnm_http_conn *conn) {
lnm_http_loop_ctx *ctx = conn->ctx;
const char *key;
size_t key_len = lnm_http_req_route_segment(&key, &ctx->req, "key") ;
lnm_linfo("main", "key: %.*s", key_len, key);
return lnm_http_step_err_done;
}
lnm_http_step_err print_step2(lnm_http_conn *conn) {
lnm_http_loop_ctx *ctx = conn->ctx;
const char *key;
size_t key_len = lnm_http_req_route_segment(&key, &ctx->req, "key") ;
lnm_linfo("main", "yuhh key: %.*s", key_len, key);
return lnm_http_step_err_done;
}
lnm_http_step_err print_step3(lnm_http_conn *conn) {
lnm_http_loop_ctx *ctx = conn->ctx;
const char *key;
size_t key_len = lnm_http_req_route_segment(&key, &ctx->req, "cool") ;
lnm_linfo("main", "cool: %.*s", key_len, key);
return lnm_http_step_err_done;
}
int main() {
lnm_http_loop *hl;
lnm_http_loop_init(&hl, NULL, ctx_init,
ctx_reset,
ctx_free);
lnm_http_router *router;
lnm_http_router_init(&router);
lnm_http_route *route;
lnm_http_router_add(&route, router, lnm_http_method_get, "/emma");
lnm_http_router_add(&route, router, lnm_http_method_get, "/:key");
lnm_http_route_step_append(route, print_step, false);
lnm_http_router_add(&route, router, lnm_http_method_get, "/:key/two");
lnm_http_route_step_append(route, print_step2, false);
lnm_http_router_add(&route, router, lnm_http_method_get, "/*cool");
lnm_http_route_step_append(route, print_step3, false);
lnm_http_loop_router_set(hl, router);
lnm_log_init_global();
lnm_log_register_stdout(lnm_log_level_debug);
printf("res = %i\n", lnm_http_loop_run(hl, 8080, 1, 0));
}