local skynet = require "skynet" local socket = require "skynet.socket" local cjson = require "cjson" local logger = require "logger" local httpd = require "http.httpd" local sockethelper = require "http.sockethelper" local urllib = require "http.url" local logger = require "logger" require "model.asset" require "model.loader" local traceback = debug.traceback local index = ... local skynet_retpack = skynet.retpack local socket_accept = socket.start local socket_close = socket.close local urllib_parse = urllib.parse local urllib_parse_query = urllib.parse_query local cjson_encode = cjson.encode local headers = { ['Access-Control-Allow-Origin'] = '*', -- 这里写允许访问的域名就可以了,允许所有人访问的话就写* ['Access-Control-Allow-Credentials'] = true, } local function response(fd, ...) local args = {...} local ok, err = httpd.write_response(sockethelper.writefunc(fd), args[1], args[2], headers) if not ok then -- if err == sockethelper.socket_error , that means socket closed. logger.error("fd = %d, %s", fd, err) end end local webpage = {} local function loadfile(url) local f = webpage[url] if f then return f end if url == "/favicon.ico" then -- discard the request return nil end local ok, ret = pcall(require, "webpage" .. url) --local ok, ret = xpcall(require, traceback, "webpage" .. url) if not ok then logger.trace("webpage: ret"..ret) return nil end webpage[url] = ret return ret end local function dispatch_request(fd, method, url, body, ipaddr, recv_header) local path, query = urllib_parse(url) local f = loadfile(path) if not f then response(fd, 404, "Not Found") return end local ok, args = pcall(urllib_parse_query, query) if method == "POST" then query = body args = cjson.decode(body) end local resp, header = f(args, ipaddr, recv_header) if resp then if type(resp) == "table" then response(fd, 200, cjson_encode(resp), header) else assert(type(resp) == "string") response(fd, 200, resp, header) end end end local CMD = {} function CMD.dispatch(fd, ipaddr) socket_accept(fd) local code, url, method, header, body = httpd.read_request(sockethelper.readfunc(fd), 8192) if code then if code == 200 then dispatch_request(fd, method, url, body, ipaddr, header) else response(fd, code) end else if url == sockethelper.socket_error then logger.warn("socket closed") else logger.error(url) end end socket_close(fd) end skynet.start(function() logger.label(string.format("", index)) skynet.dispatch("lua", function(session,_, cmd, ...) local f = assert(CMD[cmd]) if session == 0 then f(...) else skynet_retpack(f(...)) end end) end)