According to the documentation, Plug.Conn.register_before_send
registers a callback that is invoked before the request is sent. The following code prints only the "setting up" message but not "cleaning up".
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 missed from docs? What is the setup in order to make this work? Thanks in advance!
13.6) The Plug connection. This module defines a struct and the main functions for working with requests and responses in an HTTP connection. Note request headers are normalized to lowercase and response headers are expected to have lowercase keys.
In the Elixir world, Plug is the specification that enables different frameworks to talk to different web servers in the Erlang VM. If you are familiar with Ruby , Plug tries to solve the same problem that Rack does, just with a different approach.
The "conn" object (abbreviation for connection) plays a critical role in the Phoenix framework. The conn is an Elixir struct, filled with information regarding a web request.
Plug is a specification for composable modules in between web applications. It is also an abstraction layer for connection adapters of different web servers. The basic idea of Plug is to unify the concept of a "connection" that we operate on.
You are right, however you are not using the conn that has the before_send registered (don't forget that variables are immutable in Elixir.)
Change:
Plug.Conn.register_before_send(conn, fn conn ->
To:
conn = Plug.Conn.register_before_send(conn, fn conn ->
Or rewrite the function so the conn returned from register_before_send
is returned:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With