httpserver-request.lua 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. -- httpserver-request
  2. -- Part of nodemcu-httpserver, parses incoming client requests.
  3. -- Author: Marcos Kirsch
  4. local function validateMethod(method)
  5. local httpMethods = {GET=true, HEAD=true, POST=true, PUT=true, DELETE=true, TRACE=true, OPTIONS=true, CONNECT=true, PATCH=true}
  6. if httpMethods[method] then return true else return false end
  7. end
  8. local function uriToFilename(uri)
  9. return "http/" .. string.sub(uri, 2, -1)
  10. end
  11. local function parseArgs(args)
  12. local r = {}; i=1
  13. if args == nil or args == "" then return r end
  14. for arg in string.gmatch(args, "([^&]+)") do
  15. local name, value = string.match(arg, "(.*)=(.*)")
  16. if name ~= nil then r[name] = value end
  17. i = i + 1
  18. end
  19. return r
  20. end
  21. local function parseUri(uri)
  22. local r = {}
  23. local filename
  24. local ext
  25. local fullExt = {}
  26. if uri == nil then return r end
  27. if uri == "/" then uri = "/index.html" end
  28. questionMarkPos, b, c, d, e, f = uri:find("?")
  29. if questionMarkPos == nil then
  30. r.file = uri:sub(1, questionMarkPos)
  31. r.args = {}
  32. else
  33. r.file = uri:sub(1, questionMarkPos - 1)
  34. r.args = parseArgs(uri:sub(questionMarkPos+1, #uri))
  35. end
  36. filename = r.file
  37. while filename:match("%.") do
  38. filename,ext = filename:match("(.+)%.(.+)")
  39. table.insert(fullExt,1,ext)
  40. end
  41. r.ext = table.concat(fullExt,".")
  42. r.isScript = r.ext == "lua" or r.ext == "lc"
  43. r.file = uriToFilename(r.file)
  44. return r
  45. end
  46. -- Parses the client's request. Returns a dictionary containing pretty much everything
  47. -- the server needs to know about the uri.
  48. return function (request)
  49. local e = request:find("\r\n", 1, true)
  50. if not e then return nil end
  51. local line = request:sub(1, e - 1)
  52. local r = {}
  53. _, i, r.method, r.request = line:find("^([A-Z]+) (.-) HTTP/[1-9]+.[0-9]+$")
  54. r.methodIsValid = validateMethod(r.method)
  55. r.uri = parseUri(r.request)
  56. return r
  57. end