simple url parser

This commit is contained in:
Cloud Wu
2014-07-22 23:04:37 +08:00
parent d2ad63da81
commit 551d5048c4
2 changed files with 43 additions and 1 deletions

View File

@@ -2,6 +2,7 @@ local skynet = require "skynet"
local socket = require "socket"
local httpd = require "http.httpd"
local sockethelper = require "http.sockethelper"
local urllib = require "http.url"
local mode = ...
@@ -15,7 +16,20 @@ skynet.start(function()
if code ~= 200 then
httpd.write_response(sockethelper.writefunc(id), code)
else
httpd.write_response(sockethelper.writefunc(id), code , "Hello world")
local tmp = {}
if header.host then
table.insert(tmp, string.format("host: %s", header.host))
end
local path, query = urllib.parse(url)
table.insert(tmp, string.format("path: %s", path))
if query then
local q = urllib.parse_query(query)
for k, v in pairs(q) do
table.insert(tmp, string.format("query: %s= %s", k,v))
end
end
httpd.write_response(sockethelper.writefunc(id), code , table.concat(tmp,"\n"))
end
else
if url == sockethelper.socket_error then

28
lualib/http/url.lua Normal file
View File

@@ -0,0 +1,28 @@
local url = {}
local function decode_func(c)
return string.char(tonumber(c, 16))
end
local function decode(str)
local str = str:gsub('+', ' ')
return str:gsub("%%(..)", decode_func)
end
function url.parse(u)
local path,query = u:match "([^?]*)%??(.*)"
if path then
path = decode(path)
end
return path, query
end
function url.parse_query(q)
local r = {}
for k,v in q:gmatch "(.-)=([^&]*)&?" do
r[decode(k)] = decode(v)
end
return r
end
return url