Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir plug: register_before_send

Tags:

elixir

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!

like image 869
user3696012 Avatar asked Jan 11 '16 13:01

user3696012


People also ask

What is a Conn plug?

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.

What is plug in Elixir?

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.

What is Conn Elixir?

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.

What is plug in Phoenix?

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.


1 Answers

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
like image 94
Gazler Avatar answered Sep 28 '22 03:09

Gazler