From 551d5048c406c22c59293289a516e6584c45e4e5 Mon Sep 17 00:00:00 2001 From: Cloud Wu Date: Tue, 22 Jul 2014 23:04:37 +0800 Subject: [PATCH] simple url parser --- examples/simpleweb.lua | 16 +++++++++++++++- lualib/http/url.lua | 28 ++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 lualib/http/url.lua diff --git a/examples/simpleweb.lua b/examples/simpleweb.lua index f0c2855b..bfd247eb 100644 --- a/examples/simpleweb.lua +++ b/examples/simpleweb.lua @@ -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 diff --git a/lualib/http/url.lua b/lualib/http/url.lua new file mode 100644 index 00000000..ae74b099 --- /dev/null +++ b/lualib/http/url.lua @@ -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