url.lua 634 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. local url = {}
  2. local function decode_func(c)
  3. return string.char(tonumber(c, 16))
  4. end
  5. local function decode(str)
  6. local str = str:gsub('+', ' ')
  7. return str:gsub("%%(..)", decode_func)
  8. end
  9. function url.parse(u)
  10. local path,query = u:match "([^?]*)%??(.*)"
  11. if path then
  12. path = decode(path)
  13. end
  14. return path, query
  15. end
  16. function url.parse_query(q)
  17. local r = {}
  18. for k,v in q:gmatch "(.-)=([^&]*)&?" do
  19. local dk, dv = decode(k), decode(v)
  20. local oldv = r[dk]
  21. if oldv then
  22. if type(oldv) ~= "table" then
  23. r[dk] = {oldv, dv}
  24. else
  25. oldv[#oldv+1] = dv
  26. end
  27. else
  28. r[dk] = dv
  29. end
  30. end
  31. return r
  32. end
  33. return url