2014-06-17

Ruby XML RPC Server and Client (Std lib)

大概就是最近需要使用API server但找不到最simple的解法

so~ 大概看了一下std lib發現好用的東西:XML-RPC server / client

but...建議使用WEBrickServlet而非XML RPC Server...因為可以進行mount

just code :

[[server]]

require 'webrick'
require 'xmlrpc/server'
require 'json'

API_KEY = "api_v1_bata"

##service
api_servlet = XMLRPC::WEBrickServlet.new

api_servlet.set_valid_ip(
  /127\.0\.0\.1/ ,
  /192\.168\.\d{,3}\.\d{,3}/
)

api_servlet.add_handler("info") do |func|
  ans = nil
  case func
  when 'hihi'
    ans = 'yooo'
  else
    ans = 'hooo'
  end

  ans
end

api_servlet.set_default_handler do |name, *args|
  raise XMLRPC::FaultException.new(-404, "no #{name}")
end

##no_service
default_servlet = XMLRPC::WEBrickServlet.new

default_servlet.set_default_handler do |name, *args|
  '^_^...no service'
end

##main_server
$rpc_api_server = WEBrick::HTTPServer.new(
  :BindAddress => '',
  :Port => 8080,
  :AccessLog => "",
)

#...multi version or service...
$rpc_api_server.mount("/#{API_KEY}" , api_servlet )
#default
$rpc_api_server.mount('/' , default_servlet )
$rpc_api_server.start

[[client]]

require "xmlrpc/client"

API_KEY = "api_v1_bata"

server = XMLRPC::Client.new("127.0.0.1", "/#{API_KEY}", 8080)

param = server.call("info", 'hihi')
#=> yooo

param = server.call("info", '....')
#=> hooo

server = XMLRPC::Client.new("127.0.0.1", "/", 8080)

param = server.call("info", 'hihi')
#=> ^_^...no service

no gem & simple & easy :)

but 沒有辦法取得client端的remote ip...但可以limit client ip

so~ 建議intranet Server to Server使用即可

1 則留言: