BastEt 阅读(1768) 评论(0)
#include "stdafx.h"
#include

#include
#include
#include

#pragma comment(lib,"libevent2")
#pragma comment(lib,"lua5")

using namespace luabind;

luabind::object evhttp_request_get_inputhdr(lua_State *L,evhttp_request *req)
{
luabind::object result=luabind::newtable(L);
evkeyvalq *headers = evhttp_request_get_input_headers(req);
for (evkeyval *header = headers->tqh_first; header;header = header->next.tqe_next)
{
result[std::string(header->key)]=std::string(header->value);
}
return result;
}

int evhttp_add_out_hdr(evhttp_request *req,const char *key,const char *value)
{
return evhttp_add_header(evhttp_request_get_output_headers(req),key,value);
}

int evhttp_output(evhttp_request *req,const char *buflen,int bufsize)
{
evbuffer *outbuf=evhttp_request_get_output_buffer(req);
evbuffer_add(outbuf,buflen,bufsize);
return 0;
}

int evhttp_output2(evhttp_request *req,const char *buf)
{
return evhttp_output(req,buf,strlen(buf));
}

int evhttp_output3(evhttp_request *req,std::string buf)
{
return evhttp_output(req,buf.c_str(),buf.size());
}

void http_register_lua(lua_State *L)
{
module(L)
[
class_("httprequest"),
def("evhttp_request_get_command", &evhttp_request_get_command),
def("evhttp_request_get_input_header",&evhttp_request_get_inputhdr),
def("evhttp_request_get_uri",&evhttp_request_get_uri),
def("evhttp_add_output_header",&evhttp_add_out_hdr),
def("evhttp_output",&evhttp_output),
//def("evhttp_output",&evhttp_output2),
def("evhttp_output",&evhttp_output3)
];
}

//1、把所有的东东绑定进去。
//2、只绑定需要的
static void http_request_cb(struct evhttp_request *req, void *arg)
{
lua_State *L=(lua_State *)arg;
//这里要取得他的东东,或者是直接用lua来?
evhttp_cmd_type cmd=evhttp_request_get_command(req);

evbuffer *inbuf = evhttp_request_get_input_buffer(req);
//evhttp_send_reply(req, 200, "OK", NULL);


LUABIND_CHECK_STACK(L);

try
{
int ret=call_function(L, "handlehttp",req);
evhttp_send_reply(req, ret, "OK",NULL);
}
catch (luabind::error&)
{
printf("error running function handlehttp: %s",lua_tostring(L, -1));
lua_pop(L, 1);
evhttp_send_error(req, 404, "error running function handlehttp");
}
}

int main(int argc, char* argv[])
{
evthread_use_windows_threads();
event_config *base_cfg=event_config_new();
//event_config_set_flag(base_cfg,EVENT_BASE_FLAG_STARTUP_IOCP);
//event_config_set_num_cpus_hint(base_cfg,ncpucount);
event_base *evt=event_base_new_with_config(base_cfg);
evhttp *http = evhttp_new(evt);
evhttp_set_allowed_methods(http,EVHTTP_REQ_GET|EVHTTP_REQ_POST);
evhttp_bound_socket *listen_socket=evhttp_bind_socket_with_handle(http,"0.0.0.0",80);

lua_State *state=luaL_newstate();
luaL_openlibs(state);
luabind::open(state);
http_register_lua(state);
//第一次执行
luaL_loadfile(state, "D:\\kingsvn\\script\\stkcalc\\debug\\luaweb.lua");
lua_pcall(state, 0, LUA_MULTRET, 0);
evhttp_set_gencb(http,http_request_cb,state);
event_base_dispatch(evt);
return 0;
}

发表评论
切换编辑模式