achenet

achenet

How to use GenServer with Bandit?

Hello :slight_smile:

I’m struggling to get GenServer working with Bandit.
I’d like to build a simple chat server, with a POST / endpoint which enables the user to add a message, and a GET / endpoint which enables the user to list all existing messages.

This entails having some way to store the messages on the server.
From looking around it seems that GenServer

is the simplest way to this, so I tried using that.
My (very noob) code can be found here:

Basically, in lib/wusup.ex I have my handlers defined, and in lib/wusup/messages.ex I’ve tried to implement the message list following the documentation of the GenServer module.

# lib/wusup.ex
defmodule Wusup do
  use Plug.Router
  require Logger
  require EEx

  EEx.function_from_file(:def, :index, "client/index.html.eex", [:messages, :who])

  plug :match
  plug :dispatch

  get "/" do
    Logger.info("GET /")
    pid = GenServer.whereis(Wusup.Messages)
    messages = Wusup.Messages.list(pid)
    html_string = index(messages, "Ariel")
    Logger.info(html_string)
    put_resp_content_type(conn, "text/html")
    send_resp(conn, 200, html_string)
  end

  post "/" do
    Logger.info("POST /")
    GenServer.call(Messages, {:post, "new message :)"})
    # TODO
  end

  match _ do
    Logger.warning("unknown path: #{conn.request_path}")
    send_resp(conn, 404, "Not found")
  end
end

# lib/wusup/messages.ex
defmodule Wusup.Messages do
  # implement basic GenServer message store
  use GenServer

  # client side
  def start_link(default) do
    GenServer.start_link(__MODULE__, default)
  end

  def list(pid) do
    {:reply, output, _} = GenServer.call(pid, :list)
    output
  end
  

  # server callbacks
  @impl true
  def init(elements) do
    initial_state = String.split(elements, ".", trim: true)
    {:ok, initial_state}
  end

  @impl true
  def handle_call(:list, _from, state) do
    output = state
    {:reply, output, state}
  end

  @impl true
  def handle_cast({:post, message}, state) do
    new_state = [message | state]
    {:noreply, new_state}
  end

end

My lib/wusup/application.ex file, which in theory should be helping the two modules play well together, is

# lib/wusup/application.ex
defmodule Wusup.Application do
  # See https://hexdocs.pm/elixir/Application.html
  # for more information on OTP Applications
  @moduledoc false

  use Application

  @impl true
  def start(_type, _args) do
    children = [
      {Bandit, plug: Wusup, scheme: :http, port: 4000},
      {Wusup.Messages, "test message 1, test message two, gansta"}
    ]

    opts = [strategy: :one_for_one, name: Wusup.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

However, when I run the code and try to access localhost:4000 with my browser, I get the following error:


15:32:22.486 [error] ** (exit) exited in: GenServer.call(nil, :list, 5000)
    ** (EXIT) no process: the process is not alive or there's no process currently associated with the given name, possibly because its application isn't started
    (elixir 1.17.3) lib/gen_server.ex:1121: GenServer.call/3
    (wusup 0.1.0) lib/wusup/messages.ex:11: Wusup.Messages.list/1
    (wusup 0.1.0) lib/wusup.ex:14: anonymous fn/2 in Wusup.do_match/4
    (wusup 0.1.0) deps/plug/lib/plug/router.ex:246: anonymous fn/4 in Wusup.dispatch/2
    (telemetry 1.3.0) /home/ariel/wd/wusup/deps/telemetry/src/telemetry.erl:324: :telemetry.span/3
    (wusup 0.1.0) deps/plug/lib/plug/router.ex:242: Wusup.dispatch/2
    (wusup 0.1.0) lib/wusup.ex:1: Wusup.plug_builder_call/2
    (bandit 1.8.0) lib/bandit/pipeline.ex:131: Bandit.Pipeline.call_plug!/2


so it seems like I’ve made some basic error with processes here.
How can I fix it?

Also, if there is any documentation (besides the official Elixir docs) or examples/tutorials y’all could recommend, or if y’all have any tips for improving my codebase, please don’t hesitate to let me know :wink:

Marked As Solved

garrison

garrison

If you look at the docs for whereis/1 you will see that it returns nil if a registered process is not found with that name.

Because you are calling GenServer.whereis(name) and then using the result in GenServer.call(), you are attempting to call a process named nil. But there is no process named nil (and actually there cannot be, as this is not allowed), hence the error.

As mentioned above the reason is you have not registered the process with a name, and you can read those docs to see how to do that. But, also, you do not need to call whereis() to get the pid because GenServer.call(:some_name, ...) will resolve the name on its own. Actually, you can call send(:some_name, "some message") to send a message directly to a registered name, so there is no resolution needed at all.

Also Liked

derek-zhou

derek-zhou

There are many things wrong with your code, number one being you did not register your GenServer with a name. Name registration is descripbed in the documentation you linked:

My suggestion is not to read more documentation, but to read current documentation well.

achenet

achenet

Thank you for the replies ^^

I’ll take the time to re-read the doc more carefully.

Last Post!

achenet

achenet

Thank you for the replies ^^

I’ll take the time to re-read the doc more carefully.

Where Next?

Popular in Questions Top

JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

Other popular topics Top

grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 54006 488
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 40042 209
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New

We're in Beta

About us Mission Statement