----------------------------------------------------------------------------- -- modified by Michael Palmer from: -- JSONRPC4Lua: JSON RPC client calls over http for the Lua language. -- json.rpc Module. -- Author: Craig Mason-Jones -- Homepage: http://json.luaforge.net/ -- Version: 0.9.40 -- This module is released under the MIT License (MIT). -- -- REQUIREMENTS: -- Lua socket 2.0 (http://www.cs.princeton.edu/~diego/professional/luasocket/) -- mol2chemfig_dkjson.lua -- compat-5.1 if using Lua 5.0. ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Imports and dependencies ----------------------------------------------------------------------------- local json = require("mol2chemfig_dkjson") local http = require("socket.http") local assert = assert local require = require local string = string local table = table local setmetatable = setmetatable local unpack = unpack local base = _G module("mol2chemfig_jsonrpc") ----------------------------------------------------------------------------- -- PUBLIC functions ----------------------------------------------------------------------------- function proxy(url) local serverProxy = {} local proxyMeta = { __index = function(t, key) return function(...) return call(url, key, unpack(arg)) end end } setmetatable(serverProxy, proxyMeta) return serverProxy end function call(url, method, ...) assert(method,'method param is nil to call') local JSONRequestArray = { id = "httpRequest", method = method, params = arg } local httpResponse, result, code local jsonRequest = json.encode(JSONRequestArray) local ltn12 = require('ltn12') local resultChunks = {} httpResponse, code = http.request( { url = url, sink = ltn12.sink.table(resultChunks), method = 'POST', headers = { ['content-type']='text/plain', ['content-length']=string.len(jsonRequest) }, source = ltn12.source.string(jsonRequest) } ) httpResponse = table.concat(resultChunks) -- Check the http response code if (code~=200) then return nil, "HTTP ERROR: " .. code end -- And decode the httpResponse and check the JSON RPC result code result = json.decode( httpResponse ) if result.result then return result.result, nil else return nil, result.error end end