Advertisement
Guest User

json4lua's rpc.lua translation to minetest

a guest
Aug 29th, 2017
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.27 KB | None | 0 0
  1. function rpc.call(url, method, ...)
  2.   local JSONRequestArray = {
  3.     id=tostring(math.random()),
  4.     ["method"]=method,
  5.     params = ...
  6.   }
  7.   local httpResponse, result , code
  8.   local jsonRequest = minetest.write_json(JSONRequestArray)
  9.   -- We use the sophisticated http.request form (with ltn12 sources and sinks) so that
  10.   -- we can set the content-type to text/plain. While this shouldn't strictly-speaking be true,
  11.   -- it seems a good idea (Xavante won't work w/out a content-type header, although a patch
  12.   -- is needed to Xavante to make it work with text/plain)
  13.   local ltn12 = require('ltn12')
  14.   local resultChunks = {}
  15.   httpResponse, code = http.request(
  16.     { ['url'] = url,
  17.       sink = ltn12.sink.table(resultChunks),
  18.       method = 'POST',
  19.       headers = { ['content-type']='text/plain', ['content-length']=string.len(jsonRequest) },
  20.       source = ltn12.source.string(jsonRequest)
  21.     }
  22.   )
  23.   httpResponse = table.concat(resultChunks)
  24.   -- Check the http response code
  25.   if (code~=200) then
  26.     return nil, "HTTP ERROR: " .. code
  27.   end
  28.   -- And decode the httpResponse and check the JSON RPC result code
  29.   result = minetest.parse_json( httpResponse )
  30.   if result.result then
  31.     return result.result, nil
  32.   else
  33.     return nil, result.error
  34.   end
  35. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement