2017-08-01 7 views
0

APIへの接続をフィルタリングしようとしています。私mix.exsプラグでAPI接続をフィルタリングする

私が追加しました:

pipeline :some_validation do 
    plug VerifyLogicPlug 
end 

### INSIDE MY SCOPE: 

    pipe_through [:some_validation, :previous_pipeline] 

私のプラグは次のようになります。

defmodule VerifyLogicPlug do 

    import Plug.Conn 

    def init(options), do: options 

    def call(conn, _options) do 
    if some_logic do 
     respond_blocked(conn) 
    else 
     conn # Continue the normal execution of the pipeline 
    end 
    end 

    defp respond_blocked(conn) do 
    response = %{ 
     error: %{ 
     status: 401, 
     code: "BLOCKED", 
     title: "BLOCKED" 
     } 
    } 

    conn 
    |> put_resp_content_type("application/json") 
    |> send_resp(status, Poison.encode!(response)) 
    halt(conn) # I've tried both with and without this line 
    end 
end 

私はAPIにおいて所望の応答を得る:

{ 
    "error": { 
     "title": "BLOCKED", 
     "status": 401, 
     "code": "BLOCKED" 
    } 
} 

しかし、中に私がhalt(conn)を使用するかどうかによって、サーバーにいくつかのエラーが発生します。 halt(conn)で :halt(conn)なし

[error] #PID<0.1003.0> running MyProject.Endpoint terminated 
Server: localhost:4000 (http) 
Request: GET (...) 
** (exit) an exception was raised: 
    ** (Plug.Conn.NotSentError) a response was neither set nor sent from the connection 

[error] #PID<0.1404.0> running MyProject.Endpoint terminated 
Server: localhost:4000 (http) 
Request: GET (...) 
** (exit) an exception was raised: 
    ** (Plug.Conn.AlreadySentError) the response was already sent 

私が欲しいものは、(私が思う)halt(conn)を使用するが、応答が送信されているとして、Plug.Conn.NotSentErrorを得ることはありませんです。何が欠けているかのヒント?

ありがとうございます!

答えて

1

あなたは応答を2回送信しています。

変更(私はblock_requestに名前を変更することをお勧め)respond_blockへ:

conn 
|> put_resp_content_type("application/json") 
|> send_resp(status, Poison.encode!(response)) 
|> halt() 
+0

ああ、私は参照してください!だから違いは私のコードでは、私はパラメータとして元の 'conn'を使って'停止 'しており、パイプラインを通して変更された' conn'では 'halt'をやっています。初心者のミス。ありがとう! – Alan

+0

アプリケーションの他の部分を見る必要があるので、問題がどのようなものかを正確に言うことは難しいです。 AlreadySentErrorの発生方法を理解するには、ここでPlug.Connのソースコードを確認してください。https://github.com/elixir-plug/plug/blob/v1.4.3/lib/plug/conn.ex#L388 –

関連する問題