Last active
November 15, 2016 01:37
-
-
Save felipecruz/37f657f97a80718c7630af4c78e37e83 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 "Python.h" | |
#include "lwan/lwan.h" | |
/* | |
Compile with: | |
gcc `python3-config --cflags` -I/usr/local/include/lwan /usr/local/lib/liblwan.a `python3-config --ldflags` server.c -lz -o pylw | |
Run with: | |
./pylw wsgi.py | |
wsgi.py | |
def app(environ): | |
print("App() {}".format(environ)) | |
*/ | |
PyObject *wsgi_handler = NULL; | |
static lwan_http_status_t | |
request_handler(lwan_request_t *request, | |
lwan_response_t *response) | |
{ | |
const char *ip_address; | |
char ip_address_buf[INET6_ADDRSTRLEN]; | |
PyObject *resp; | |
PyObject *environ = PyDict_New(); | |
ip_address = lwan_request_get_remote_address(request, ip_address_buf); | |
if (UNLIKELY(!ip_address)) | |
return HTTP_INTERNAL_ERROR; | |
PyGILState_STATE _st = PyGILState_Ensure(); | |
if (wsgi_handler && PyCallable_Check(wsgi_handler)) { | |
Py_XINCREF(environ); | |
PyDict_SetItemString(environ, "ip", Py_BuildValue("s", ip_address_buf)); | |
resp = PyObject_CallFunctionObjArgs(wsgi_handler, environ, NULL); | |
if (!resp) { | |
PyErr_Print(); | |
} | |
Py_XDECREF(environ); | |
} else { | |
PyErr_Print(); | |
} | |
printf("%s\n", ip_address_buf); | |
PyGILState_Release(_st); | |
return HTTP_OK; | |
} | |
int main(int argc, char **argv) { | |
int i; | |
lwan_t l; | |
lwan_config_t c; | |
PyObject *pName, *pModule; | |
Py_Initialize(); | |
PyEval_InitThreads(); | |
wchar_t *program = Py_DecodeLocale(argv[0], NULL); | |
pName = PyUnicode_DecodeFSDefault(argv[1]); | |
pModule = PyImport_Import(pName); | |
Py_DECREF(pName); | |
Py_XINCREF(pModule); | |
if (program == NULL) { | |
fprintf(stderr, "Fatal error: cannot decode argv[0]\n"); | |
return -1; | |
} | |
Py_SetProgramName(program); | |
if (pModule) { | |
wsgi_handler = PyObject_GetAttrString(pModule, "app"); | |
Py_XINCREF(wsgi_handler); | |
} else { | |
PyErr_Print(); | |
return -1; | |
} | |
c = *lwan_get_default_config(); | |
c.listener = strdup("*:8080"); | |
const lwan_url_map_t default_map[] = { | |
{ .prefix = "/", .handler = request_handler}, | |
}; | |
lwan_init_with_config(&l, &c); | |
lwan_set_url_map(&l, default_map); | |
Py_BEGIN_ALLOW_THREADS | |
lwan_main_loop(&l); | |
lwan_shutdown(&l); | |
Py_END_ALLOW_THREADS | |
Py_XDECREF(wsgi_handler); | |
Py_XDECREF(pModule); | |
Py_Finalize(); | |
PyMem_RawFree(program); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment