启动节点过程中灵药然后返回一个HTTP请求
问题描述:
结果使用Porcelain和HTTPoison我想做到以下几点:启动节点过程中灵药然后返回一个HTTP请求
启动节点服务器
发送一个HTTP请求到节点过程
关闭过程
回报次的结果E分别请求
我一直在试图像下面的内容:
require HTTPoison
alias Porcelain.Process, as: Proc
alias Porcelain.Result, as: Res
def request do
cmd = "node node_app/src/index.js"
opts = [out: {:send, self()}]
proc = %Proc{pid: pid} = Porcelain.spawn_shell(cmd, opts)
receive do
{^pid, :data, :out, log} ->
IO.puts "Node log => #{log}"
# only if log contains "running" should I send the request
if String.contains?(log, "running") do
IO.puts "Requesting..."
%HTTPoison.Response{body: body} = HTTPoison.get! @root_url <> "/collection"
Proc.stop(proc)
end
{^pid, :result, %Res{status: status} = res} ->
nil
end
Proc.await proC# wait for the process to terminate
body # return body of request
end
的一个问题是,我没有对的时候我可以返回了的接收控制。
我得到了一个灵丹妙药的警告,表明身体可能没有被定义,我想避免。
我该怎么做呢?有没有更好的方法来做到这一点?
在此先感谢您的帮助
答
有两个毛刺与此代码:首先,应该在任何情况下停止衍生的进程。
次要的,你应该把整个结果receive
绑定到变量上。像这样的东西应该工作(未经测试):
result = receive do
{^pid, :data, :out, log} ->
IO.puts "Node log => #{log}"
# only if log contains "running" should I send the request
if String.contains?(log, "running") do
IO.puts "Requesting..."
HTTPoison.get! @root_url <> "/collection"
end
{^pid, :result, %Res{status: status} = res} ->
nil
end
Proc.stop(proc)
with %HTTPoison.Response{body: body} <- result, do: body
最后Kernel.SpecialForms.with/1
将有效地返回什么,如果匹配成功不匹配预期Response
,或body
。
旁注:警告的确是未来的运行时错误。 body
在receive
的范围内定义,使其在关闭范围内不可见。