【置顶】Http服务器-第五步加入lua来编写动态网页

梦想游戏人
目录:
C/C++

原打算加入php支持,遇到了点小问题,因此打算用lua来编写动态网页

基本原理:通过分析url请求,吧请求参数传递给lua处理,lua返回处理后的数据,然后C++端返回给浏览器

ScriptCore.cpp

#include "ScriptCore.h"
#include <string>
#include <iostream>
#include <vector>
#include "Defs.h"
#include <mutex>
using namespace  std;

static std::mutex _script_mutex;


std::string  ScriptCore::exec(std::string file, std::string param)
{
///	std::lock_guard<std::mutex> locker(_script_mutex);

//	luaL_dostring(l, "print(\" hello lua\")");


//	return  "HttpHandler";


	int top = lua_gettop(l);



	lua_getglobal(l, "HttpHandler"); // get   Interface in lua




	//parse param ,  as "name=5" will be push
	int p,len = 0;

	vector<string> params;

	do
	{
 
		p = param.find("&");
		if (p == string::npos)
		{
			params.push_back(param);
			break;
		}
		else
		{
			string sub = param.substr(len, p);
			param = param.substr(p + 1, -1);
			params.push_back(sub);
		}
	} while (true);


	//push param to stack
	lua_pushstring(l,file.c_str());

	for (auto &s : params)
	{
		lua_pushstring(l, s.c_str());
	}


	lua_call(l, params.size()+1, 1);
	std::string ret = lua_tostring(l, lua_gettop(l));
//	lua_pop(l, 1);
	lua_settop(l, top);

	return ret;

	return  "ScriptCore.h";
}
ScriptCore::ScriptCore()
{
	this->initLua();
}

ScriptCore::~ScriptCore()
{
	lua_close(l);

}

ScriptCore* ScriptCore::getInstance()
{
	static ScriptCore*ins = nullptr;
	if (ins == nullptr)
	{
		ins = new ScriptCore;
	}
	return ins;
}


void ScriptCore::initLua()
{
	l = lua_open();
	luaL_openlibs(l);

	luaL_dofile(l, "HttpHandler.lua");

}

服务配置文件 server_config.lua

--配置服务类型和关联的lua script
local t={};

t["get"]="script/get";
t["login"]="script/login";
t["MsgBoard"]="script/MsgBoard";
return t;
local t={};

function t:doRequest(p)
	
	return   " login succ   "  .. p["name"]  

end

return t;

运行结果

这样就能用lua 像用 php jsp 之类的来写动态网页了,实现自己的http服务,

当然还要提供一些C++接口给lua 比如SQL 等服务

Scroll Up