QUOTE: Life is a journey, not a destination.

ctl

Static template generator for C

libctl.h (1441B)


      1#ifndef LIB_CTL_H
      2#define LIB_CTL_H
      3
      4#include <libhttp.h>
      5#include <libstr.h>
      6
      7typedef struct ctl_ctx ctl_ctx_t;
      8typedef void (*ctl_fn_t)(char **ctl_out, ctl_ctx_t ctx);
      9
     10struct ctl_ctx {
     11  http_req_t *request;
     12  char *title;
     13  ctl_fn_t fn;
     14  void *data;
     15};
     16
     17void ctl_init(ctl_fn_t fn);
     18http_resp_t ctl_serve_page(http_req_t *request, const char *title, ctl_fn_t fn, void *data);
     19http_resp_t ctl_serve_component(http_req_t *request, ctl_fn_t fn, void *data);
     20
     21#ifdef LIB_CTL_IMPL
     22
     23static ctl_fn_t ctl_fn = NULL;
     24
     25void ctl_init(ctl_fn_t fn) {
     26  ctl_fn = fn;
     27}
     28
     29http_resp_t ctl_serve_page(http_req_t *request, const char *title, ctl_fn_t fn, void *data) {
     30  char *html = NULL;
     31  ctl_ctx_t ctx = {
     32    .request = request,
     33    .title = title,
     34    .fn = fn,
     35    .data = data,
     36  };
     37  ctl_fn(&html, ctx);
     38  http_resp_t response = http_resp_create(HTTP_STATUS_OK);
     39  http_resp_header(&response, "Content-Type", "text/html");
     40  http_resp_body(&response, html, strlen(html));
     41  free(html);
     42  return response;
     43}
     44
     45http_resp_t ctl_serve_component(http_req_t *request, ctl_fn_t fn, void *data) {
     46  char *html = NULL;
     47  ctl_ctx_t ctx = {
     48    .request = request,
     49    .data = data,
     50  };
     51  fn(&html, ctx);
     52  http_resp_t response = http_resp_create(HTTP_STATUS_OK);
     53  http_resp_header(&response, "Content-Type", "text/html");
     54  http_resp_body(&response, html, strlen(html));
     55  free(html);
     56  return response;
     57}
     58
     59#endif /* LIB_CTL_IMPL */
     60#endif /* LIB_CTL_H */