Simple example using server and client cookies.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#define CONTENT_TYPE "text/html; charset=utf-8"
#define BEGIN_PAGE "<html><head><title>Cookies</title></head><body>"
#define END_PAGE "</body></html>"
#define INITIAL_PAGE BEGIN_PAGE "Use F5 to refresh this page ..." END_PAGE
#define COUNT_PAGE BEGIN_PAGE "Refresh number: %d" END_PAGE
#define COOKIE_NAME "refresh_count"
static int strtoint(const char *str) {
if (!str)
return 0;
return (int) strtol(str, NULL, 10);
}
static void req_cb(__SG_UNUSED
void *cls,
struct sg_httpreq *req,
char str[100];
int count;
return;
}
count = cookies ? strtoint(
sg_strmap_get(*cookies, COOKIE_NAME)) : 0;
if (count == 0) {
snprintf(str, sizeof(str), INITIAL_PAGE);
count = 1;
} else {
snprintf(str, sizeof(str), COUNT_PAGE, count);
count++;
}
snprintf(str, sizeof(str), "%d", count);
}
int main(int argc, const char *argv[]) {
uint16_t port;
if (argc != 2) {
printf("%s <PORT>\n", argv[0]);
return EXIT_FAILURE;
}
port = strtol(argv[1], NULL, 10);
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))
int sg_httpres_set_cookie(struct sg_httpres *res, const char *name, const char *val)
void sg_httpsrv_free(struct sg_httpsrv *srv)
struct sg_strmap ** sg_httpreq_cookies(struct sg_httpreq *req)
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)
const char * sg_strmap_get(struct sg_strmap *map, const char *name)