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

原打算加入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;

 

登陆服务 login.lua



local t={};

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

end

return t;

 

运行结果

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

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

转载于:https://my.oschina.net/kkkkkkkkkkkkk/blog/746684

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值