Created
March 30, 2017 19:11
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 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