Elixir插件:register_before_send

use*_*012 5 elixir

根据文档,Plug.Conn.register_before_send注册在发送请求之前调用的回调.以下代码仅打印"设置"消息,但不打印"清理"消息.

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
Run Code Online (Sandbox Code Playgroud)

我在文档中遗漏了什么吗?为了使这项工作有什么设置?提前致谢!

Gaz*_*ler 13

你是对的,但是你没有使用已经注册了before_send的conn(不要忘记Elixir中的变量是不可变的.)

更改:

Plug.Conn.register_before_send(conn, fn conn -> 
Run Code Online (Sandbox Code Playgroud)

至:

conn = Plug.Conn.register_before_send(conn, fn conn -> 
Run Code Online (Sandbox Code Playgroud)

或者重写函数,以便返回conn 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
Run Code Online (Sandbox Code Playgroud)