diff --git a/docs/nic.txt b/docs/nic.txt index 1bb9f7e..453926a 100644 --- a/docs/nic.txt +++ b/docs/nic.txt @@ -1,2 +1,33 @@ How to use the NIC: Send a digilines signal with the URL you want to download. The HTTPRequestResult table will be sent back on the same channel. + +# Examples + +## GET request with a plain url +```lua +-- request +digiline_send("nic", "http://example.com") +-- response +event.msg = { + code = 200, + succeeded = true, + data = "" +} +``` + +## GET request with parsed json response +```lua +-- request +digiline_send("nic", { + url = "http://example.com", + parse_json = true +}) +-- response +event.msg = { + code = 200, + succeeded = true, + data = { + my = "data" + } +} +``` diff --git a/nic.lua b/nic.lua index da1e70d..c717fb2 100644 --- a/nic.lua +++ b/nic.lua @@ -48,13 +48,30 @@ minetest.register_node("digistuff:nic", { action = function(pos,node,channel,msg) local meta = minetest.get_meta(pos) if meta:get_string("channel") ~= channel then return end - if type(msg) ~= "string" then return end + local url + local parse_json = false + -- parse message + if type(msg) == "string" then + -- simple string data + url = msg + elseif type(msg) == "table" and type(msg.url) == "string" then + -- config object + url = msg.url + parse_json = msg.parse_json + else + -- not supported + return + end http.fetch({ - url = msg, - timeout = 5, - user_agent = "Minetest Digilines Modem", + url = url, + timeout = 5, + user_agent = "Minetest Digilines Modem" }, function(res) + if type(res.data) == "string" and parse_json then + -- parse json data and replace payload + res.data = minetest.parse_json(res.data) + end digilines.receptor_send(pos, digilines.rules.default, channel, res) end) end