httpweb.lua 2.68 KB

local urllib = require "http.url"
require "shared.init"
require "utils.init"
local sockethelper = require "http.sockethelper"
local httpd = require "http.httpd"
skynet = require "skynet"
redisproxy = require "shared.redisproxy"
netpack = require "skynet.netpack"
datacenter = require "skynet.datacenter"
mcast_util = require "services/mcast_util"
csvdb = require "shared.csvdata"

local socket = require "skynet.socket"

require "shared.init"
require "utils.init"
require "ProtocolCode"
require "skynet.manager"
require "RedisKeys"
require "GlobalVar"

SendPacket = function(...) end
rpcAgent = function(...) end
rpcParter = function(...) end
rpcRole = function(...) end
rpcUnion = function(...) end
rpcOtherUnion = function(...) end

local table = table
local string = string

skynet.register_protocol {
	name = "role",
	id = 101,
	pack = skynet.pack,
	unpack = skynet.unpack,
}

local port = ...
port = tonumber(port)

local key = "zhaolu1234dangge"
local function response(id, code, body)
	local ok, err = httpd.write_response(sockethelper.writefunc(id), code, body, {
		["Connection"] = "Close",
	})
	if not ok then
		-- if err == sockethelper.socket_error , that means socket closed.
		skynet.error(string.format("fd = %d, %s", id, err))
	end
end


local CMD = require "actions.HttpAction"

local function start()
	globalCsv = csvdb["GlobalDefineCsv"]
	
	
	local listen_socket = socket.listen("0.0.0.0", port)
	print("Listen web port " .. port)
	socket.start(listen_socket , function(id, addr)
		socket.start(id)
		local code, url, method, header, body = httpd.read_request(sockethelper.readfunc(id), 8192)
		if code then
			if code ~= 200 then
				response(id, code)
			else
				local path, query = urllib.parse(url)
				local cmd = path:match("([^/]+)")
				if not CMD[cmd] or not query then
					response(id, 404)
					socket.close(id) 
					return 
				end
				local query = urllib.parse_query(query)
				-- if query.key ~= key then
				-- 	response(id, 404)
				-- 	socket.close(id) 
				-- 	return 
				-- end
				local content = CMD[cmd](query, body)
				if not content then
					code = 404
				end
				response(id, code, tostring(content))
			end
		else
			if url == sockethelper.socket_error then
				skynet.error("socket closed")
			else
				skynet.error(url)
			end
		end
		socket.close(id)
	end)

	-- 注册全服广播
	local channels = {}
	for i = 1, 10 do
		local channel = datacenter.get("MC_W_CHANNEL" .. i)
		if channel then
			table.insert(channels, channel)
		end
	end
	if #channels > 0 then
		mcast_util.sub_worlds(channels)
	end
end

local function __init__()
	skynet.dispatch("lua", function(_,_, command, ...)
		if command == "start" then
			skynet.ret(skynet.pack(start(...)))
		end
	end)
end

skynet.start(__init__)