Created
October 21, 2015 09:39
-
-
Save upbit/2cec355544752fc7708a to your computer and use it in GitHub Desktop.
Module for rpc call remote api@node functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule ApiBridge do | |
@moduledoc """ | |
Module for rpc call remote api@node functions. | |
""" | |
@defualt_rpc_timeout 3000 | |
@doc """ | |
rpc macro for api call | |
""" | |
defmacro rpc(exp, timeout \\ @defualt_rpc_timeout) do | |
rpc_node = rpc_nodename('api') | |
{{:., _, [module, function]}, _, args} = exp | |
quote do | |
:rpc.call(unquote(rpc_node), unquote(module), unquote(function), unquote(args), unquote(timeout)) | |
end | |
end | |
@doc """ | |
rpc macro for api call, throw RuntimeError if {:error, _} returned. | |
""" | |
defmacro rpc!(exp, timeout \\ @defualt_rpc_timeout) do | |
rpc_node = rpc_nodename('api') | |
{{:., _, [module, function]}, _, args} = exp | |
quote do | |
case :rpc.call(unquote(rpc_node), unquote(module), unquote(function), unquote(args), unquote(timeout)) do | |
{:ok, result} -> result | |
{:error, reason} -> raise "rpc #{unquote(module)}:#{unquote(function)}/#{unquote(length(args))} error: #{reason}" | |
end | |
end | |
end | |
# priv | |
@doc """ | |
> config :server, ApiBridge, rpc_node: "127.0.0.1" | |
""" | |
defp config(key) do | |
Application.get_env(:server, ApiBridge)[key] | |
end | |
@doc """ | |
return a rpc node name with prefix, use eth0 ip if rpc_node not exist | |
""" | |
defp rpc_nodename(prefix) do | |
str_ip = case config(:rpc_node) do | |
nil -> {:ok, [{:addr, tmp_ip}]} = :inet.ifget('eth0', [:addr]); :inet_parse.ntoa(tmp_ip) | |
conf_ip -> conf_ip | |
end | |
String.to_atom(to_string(prefix) <> "@" <> to_string(str_ip)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment