libctl.h (1499B)
1 #ifndef LIB_CTL_H 2 #define LIB_CTL_H 3 4 #include <libhttp.h> 5 #include <libstr.h> 6 7 typedef struct ctl_ctx ctl_ctx_t; 8 typedef void (*ctl_fn_t)(char **ctl_out, ctl_ctx_t ctx); 9 10 struct ctl_ctx { 11 http_request_t *request; 12 char *title; 13 ctl_fn_t fn; 14 void *data; 15 }; 16 17 void ctl_init(ctl_fn_t fn); 18 http_response_t ctl_serve_page(http_request_t *request, const char *title, ctl_fn_t fn, void *data); 19 http_response_t ctl_serve_component(http_request_t *request, ctl_fn_t fn, void *data); 20 21 #ifdef LIB_CTL_IMPL 22 23 static ctl_fn_t ctl_fn = NULL; 24 25 void ctl_init(ctl_fn_t fn) { 26 ctl_fn = fn; 27 } 28 29 http_response_t ctl_serve_page(http_request_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_response_t response = http_response_create(HTTP_STATUS_OK); 39 http_header_set(&response, "Content-Type", "text/html"); 40 http_response_body(&response, html, strlen(html)); 41 free(html); 42 return response; 43 } 44 45 http_response_t ctl_serve_component(http_request_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_response_t response = http_response_create(HTTP_STATUS_OK); 53 http_header_set(&response, "Content-Type", "text/html"); 54 http_response_body(&response, html, strlen(html)); 55 free(html); 56 return response; 57 } 58 59 #endif /* LIB_CTL_IMPL */ 60 #endif /* LIB_CTL_H */