Simple example showing how to use the router feature in a HTTP server.
#include <stdio.h>
#include <stdlib.h>
struct holder {
};
static int route_download_file_cb(void *cls, const char *name,
const char *val) {
sprintf(cls, "%s: %s", name, val);
return 0;
}
static void route_home_cb(__SG_UNUSED
void *cls,
struct sg_route *route) {
holder->res,
"<html><head><title>Home</title></head><body>Home</body></html>",
"text/html", 200);
}
static void route_download_cb(__SG_UNUSED
void *cls,
struct sg_route *route) {
char file[256];
memset(file, 0, sizeof(file));
if (strlen(file) == 0)
strcpy(file, "Download");
page, "<html><head><title>Download</title></head><body>%s</body></html>",
file);
}
static void route_about_cb(__SG_UNUSED
void *cls,
struct sg_route *route) {
holder->res,
"<html><head><title>About</title></head><body>About</body></html>",
"text/html", 200);
}
static void req_cb(__SG_UNUSED
void *cls,
struct sg_httpreq *req,
struct holder holder = {req, res};
res, "<html><head><title>Not found</title></head><body>404</body></html>",
"text/html", 404);
}
int main(void) {
sg_routes_add(&routes,
"/download/(?P<file>[a-z]+)", route_download_cb, NULL);
return EXIT_FAILURE;
}
fprintf(stdout, "Server running at http://localhost:%d\n",
fflush(stdout);
getchar();
return EXIT_SUCCESS;
}
struct sg_httpsrv * sg_httpsrv_new(sg_httpreq_cb cb, void *cls) __attribute__((malloc))
void sg_httpsrv_free(struct sg_httpsrv *srv)
const char * sg_httpreq_path(struct sg_httpreq *req)
#define sg_httpres_send(res, val, content_type, status)
Definition sagui.h:1032
bool sg_httpsrv_listen(struct sg_httpsrv *srv, uint16_t port, bool threaded)
uint16_t sg_httpsrv_port(struct sg_httpsrv *srv)
int sg_router_dispatch(struct sg_router *router, const char *path, void *user_data)
int sg_routes_cleanup(struct sg_route **routes)
void * sg_route_user_data(struct sg_route *route)
struct sg_router * sg_router_new(struct sg_route *routes) __attribute__((malloc))
bool sg_routes_add(struct sg_route **routes, const char *pattern, sg_route_cb cb, void *cls)
void sg_router_free(struct sg_router *router)
int sg_route_vars_iter(struct sg_route *route, sg_vars_iter_cb cb, void *cls)
int const char * sg_str_content(struct sg_str *str)
struct sg_str * sg_str_new(void) __attribute__((malloc))
void sg_str_free(struct sg_str *str)
int sg_str_printf(struct sg_str *str, const char *fmt,...) __attribute__((format(printf