Created
November 8, 2012 21:26
-
-
Save HarryR/4041748 to your computer and use it in GitHub Desktop.
Example of basic libevent http server in Racket using FFI
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
#lang racket | |
(require ffi/unsafe | |
ffi/unsafe/define) | |
(define-ffi-definer define-libevent (ffi-lib "libevent")) | |
; Event Base | |
(define evbase-ptr (_cpointer 'evbase)) | |
(define-libevent event_base_new (_fun -> evbase-ptr)) | |
(define-libevent event_base_dispatch (_fun evbase-ptr -> _void)) | |
(define-libevent event_base_free (_fun evbase-ptr -> _void)) | |
; evbuffer | |
(define evbuffer-ptr (_cpointer 'evbuffer)) | |
(define-libevent evbuffer_new (_fun -> evbuffer-ptr)) | |
(define-libevent evbuffer_add (_fun evbuffer-ptr _string _intptr -> _int)) | |
(define-libevent evbuffer_free (_fun evbuffer-ptr -> _void)) | |
; evhttp | |
(define evhttp-ptr (_cpointer 'evhttp)) | |
(define-libevent evhttp_new (_fun evbase-ptr -> evhttp-ptr)) | |
(define-libevent evhttp_bind_socket (_fun evhttp-ptr _string _ushort -> _int)) | |
(define-libevent evhttp_free (_fun evhttp-ptr -> _void)) | |
(define evkeyvalq-ptr (_cpointer 'evkeyvalq)) | |
(define-libevent evhttp_add_header (_fun evkeyvalq-ptr _string _string -> _int)) | |
; evhttp requests | |
(define evhttp-request-ptr (_cpointer 'evhttp_request)) | |
(define-libevent evhttp_send_reply (_fun evhttp-request-ptr _int _string evbuffer-ptr -> _void)) | |
(define-libevent evhttp_request_get_input_headers (_fun evhttp-request-ptr -> evkeyvalq-ptr)) | |
(define-libevent evhttp_request_get_output_headers (_fun evhttp-request-ptr -> evkeyvalq-ptr)) | |
(define _evhttp_callback (_fun evhttp-request-ptr _gcpointer -> _void)) | |
(define-libevent evhttp_set_cb (_fun evhttp-ptr _string _evhttp_callback _pointer -> _int)) | |
(define (http-handler request arg) | |
(void | |
(evhttp_add_header (evhttp_request_get_output_headers request) "Content-Type" "text/plain") | |
(let ([buffer (evbuffer_new)]) | |
(evbuffer_add buffer "Hello" 5) | |
(evhttp_send_reply request 200 "OK" buffer) | |
(evbuffer_free buffer)))) | |
(define (main) | |
(let ([base (event_base_new)]) | |
(let ([httpd (evhttp_new base)]) | |
(evhttp_bind_socket httpd "localhost" 8093) | |
(evhttp_set_cb httpd "/" http-handler #f) | |
(event_base_dispatch base) | |
(evhttp_free httpd) | |
(event_base_free base)))) | |
(main) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment