Elixir plug: register_before_send

According to the documentation, it Plug.Conn.register_before_sendregisters a callback that is called before sending the request. The following code prints only the “setup” message, but does not “clear”.

defmodule MyRouter do
  use Plug.Router

  # Starts the server
  def start do
    Plug.Adapters.Cowboy.http MyRouter, []
  end

  plug :my_handle # custom plug
  plug :match
  plug :dispatch

  def my_handle(conn, _opts) do
    Plug.Conn.register_before_send(conn, fn conn -> 
      # Doesn't show up in console.
      IO.puts "== cleaning up =="
      conn
    end)
    # This is printed to the console.
    IO.puts "== setting up =="
    conn
  end

  get "/" do
    send_resp(conn, 200, "world")
  end

  match _ do
    send_resp(conn, 404, "oops")
  end
end

Is there anything I skipped from the docs? What is customization to make this work? Thanks in advance!

+4
source share
1 answer

You are correct, however, you are not using conn which has before_send registered (do not forget that the variables are immutable in Elixir.)

Edit:

Plug.Conn.register_before_send(conn, fn conn -> 

To:

conn = Plug.Conn.register_before_send(conn, fn conn -> 

Or rewrite the function so that the value returned from register_before_send:

def my_handle(conn, _opts) do
  IO.puts "== setting up =="
  Plug.Conn.register_before_send(conn, fn conn -> 
    # Doesn't show up in console.
    IO.puts "== cleaning up =="
    conn
  end)
end
+11
source

Source: https://habr.com/ru/post/1623756/


All Articles