Blame view

src/services/httpweb.lua 1.74 KB
3fe4471e   zhouhaihai   热更新 demo
1
2
3
4
5
6
7
8
9
10
11
  local skynet = require "skynet"
  local socket = require "skynet.socket"
  local httpd = require "http.httpd"
  local sockethelper = require "http.sockethelper"
  local urllib = require "http.url"
  require "shared.init"
  require "utils.init"
  
  local table = table
  local string = string
  
5e5d7680   zhouhaihai   热更新 优化
12
  local port = ...
3fe4471e   zhouhaihai   热更新 demo
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
  port = tonumber(port)
  
  local key = "zhaolu1234dangge"
  local function response(id, ...)
  	local ok, err = httpd.write_response(sockethelper.writefunc(id), ...)
  	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()
  	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, content)
  			end
  		else
  			if url == sockethelper.socket_error then
  				skynet.error("socket closed")
  			else
  				skynet.error(url)
  			end
  		end
  		socket.close(id)
  	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__)