aboutsummaryrefslogtreecommitdiff
path: root/examples/cookie.c
blob: c64ca0c54fe6bd8ed1acfd3aa44ee6e10371828e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* Basic example of cookie handling through response headers.
 * It lists all recieved cookies and set one via magi_response,
 * showing work with headers in magi.
 */
#include <magi.h>


void list_cookies(magi_request *r)
{
    magi_cookies *current;
    printf("Cookies:");
    /* Iterate through all cookies in request to show them in body: */
    for (current = r->cookies; current; current = current->next) {
        magi_cookie *c = &current->item;
        printf("<br />[%s]=[%s]", c->name, c->data);
    }
}

void response(magi_request *r)
{
    magi_response head;
    magi_response_init(&head);  /* Setting defaults. */
    /* Set cookie "cookie" with value "monster" on clientside: */
    magi_response_cookie(&head, "cookie", "monster");
    magi_response_free(&head);  /* Send headers and start sending body: */
    printf("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' "
           "'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>"
           "<html xmlns='http://www.w3.org/1999/xhtml'>"
           "<head><title>Cookie Listing and Setting</title></head>"
           "<body><p>");
    list_cookies(r);
    printf("</p></body></html>");
}

int main()
{
    magi_request request;
    magi_request_init(&request);  /* Setting defaults. */
    if (magi_parse(&request)) {   /* If parsing was done successful */
        response(&request);       /* we need to response the request. */
    } else {                      /* And display error overwise: */
        magi_error_response(request.error);
    }
    magi_request_free(&request);  /* Don't forget to free everything after. */
    return 0;
}