How to get post parameters from http request in lua sent to NodeMCU

馋奶兔 提交于 2019-12-02 11:56:37

For the sake of completeness, here is another solution I came up with:

string.gsub(request, "<(%a+)>([^<]+)</%a+>", function(key, val)
  print(key .. ": " .. val)
end)

A working example using the given HTTP request in your question can be seen here:

https://repl.it/repls/GlamorousAnnualConferences

This function allows you to extract text from between two string delimiters:

function get_text (str, init, term)
   local _, start = string.find(str, init)
   local stop = string.find(str, term)
   local result = nil
   if _ and stop then
      result = string.sub(str, start + 1, stop - 1)
   end
   return result
end

Sample interaction:

> msg = "<action>Play</action><SetVolume>5</SetVolume>"
> get_text(msg, "<action>", "<SetVolume>")
Play</action>
> get_text(msg, "<action>", "</SetVolume>")
Play</action><SetVolume>5

This is a modification of the above function that allows nil for either of the parameters init or term. If init is nil, then text is extracted up to the term delimiter. If term is nil, then text is extracted from after init to the end of the string.

function get_text (str, init, term)
   local _, start
   local stop = (term and string.find(str, term)) or 0
   local result = nil
   if init then
      _, start = string.find(str, init)
   else
      _, start = 1, 0
   end

   if _ and stop then
      result = string.sub(str, start + 1, stop - 1)
   end
   return result
end

Sample interaction:

> msg = "<action>Play</action><SetVolume>5</SetVolume>"
> get_text(msg)
<action>Play</action><SetVolume>5</SetVolume>
> get_text(msg, nil, '<SetVolume>')
<action>Play</action>
> get_text(msg, '</action>')
<SetVolume>5</SetVolume>
> get_text(msg, '<action>', '<SetVolume>')
Play</action>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!