Created
July 29, 2010 04:28
-
-
Save tyler/497240 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <event.h> | |
#include <evhttp.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <sys/time.h> | |
typedef struct { | |
const char * uri; | |
struct evhttp_request * ev_req; | |
} Request; | |
typedef struct { | |
int code; | |
char * body; | |
size_t body_len; | |
} Response; | |
#define Bogart \ | |
Response bogart_dispatch(Request * req) | |
#define Get(path) \ | |
if(strcmp(path, req->uri) == 0) | |
#define respond(code, body) \ | |
return (Response) { code, body, strlen(body) } | |
Bogart { | |
Get("/hello") { | |
respond(200, "Goodbye World!"); | |
} | |
Get("/") { | |
respond(200, "Hello World!"); | |
} | |
} | |
void request_handler(struct evhttp_request * req, void * nothing) { | |
struct timeval t0, t1, tr; | |
gettimeofday(&t0, NULL); | |
struct evbuffer * buffer = evbuffer_new(); | |
const char * uri = evhttp_request_get_uri(req); | |
Request * request = (Request *) malloc(sizeof(Request)); | |
request->ev_req = req; | |
request->uri = uri; | |
Response response = bogart_dispatch(request); | |
evbuffer_add(buffer, response.body, response.body_len); | |
evhttp_send_reply(req, response.code, "OK", buffer); | |
evbuffer_free(buffer); | |
gettimeofday(&t1, NULL); | |
timersub(&t1, &t0, &tr); | |
printf("Request processed in: %u secs, %u usecs\n", tr.tv_sec, tr.tv_usec); | |
} | |
int main() { | |
struct event_base * base = event_init(); | |
struct evhttp * http = evhttp_new(base); | |
evhttp_bind_socket(http, "127.0.0.1", 11000); | |
evhttp_set_gencb(http, request_handler, NULL); | |
event_loop(0); | |
evhttp_free(http); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment