Skip to content

Instantly share code, notes, and snippets.

@mlankenau
Created March 30, 2017 19:11
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 mlankenau/b717ba373fc1780bdda58395f11f6321 to your computer and use it in GitHub Desktop.
Save mlankenau/b717ba373fc1780bdda58395f11f6321 to your computer and use it in GitHub Desktop.
defmodule NumberService do
import Plug.Conn
@doc "server loop"
def server(i) do
receive do
{:next, caller} ->
send caller, {:next_num, i}
server(i+1)
end
end
@doc "call server for the next number"
def client_call(pid) do
send pid, {:next, self()}
receive do
{:next_num, i} -> i
end
end
def init(options) do
# start server process
Map.put(options, :server_pid, spawn_link(__MODULE__, :server, [1]))
end
def call(conn, opts) do
num = client_call(opts.server_pid)
conn
|> put_resp_content_type("text/plain")
|> send_resp(200, "#{num}")
end
end
{:ok, _} = Plug.Adapters.Cowboy.http NumberService, %{}
receive do
:term -> :ok
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment