Skip to content

Instantly share code, notes, and snippets.

@developerworks
Forked from upbit/api_bridge.ex
Created November 3, 2015 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save developerworks/8089e43251b635c4dcac to your computer and use it in GitHub Desktop.
Save developerworks/8089e43251b635c4dcac to your computer and use it in GitHub Desktop.
Module for rpc call remote api@node functions
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