クイックリファレンス

Phoenix Plug.Conn チートシート

PhoenixのPlug.Connクイックリファレンス:リクエスト情報の取得、レスポンスヘッダーの設定、Cookie、リダイレクト、パイプラインの中断(halt)。

· 公開日

ElixirのPhoenixフレームワークにおいて、Plug.Conn は受信したHTTPリクエストと送信するレスポンスの双方をイミュータブルな構造体として表現します。

受信リクエストの検査(Inspecting Incoming Requests)

conn.host          # => "example.com"
conn.method        # => "GET", "POST", etc.
conn.path_info     # => ["users", "42"]
conn.request_path  # => "/users/42"
conn.query_string  # => "tab=activity&sort=desc"
conn.port          # => 443
conn.scheme        # => :https
conn.remote_ip     # => {127, 0, 0, 1}

# リクエストヘッダーの取得
get_req_header(conn, "authorization") # => ["Bearer token_xyz"]

HTTPレスポンスの送信(Sending HTTP Responses)

# JSON レスポンスの返却
conn
|> put_status(200)
|> json(%{status: "ok", count: 42})

# HTML レスポンスの返却
conn
|> put_status(200)
|> html("<h1>Welcome</h1>")

# プレーンテキストの返却
conn
|> put_status(404)
|> text("Not Found")

リダイレクトとフロー制御(Redirects & Flow Control)

# 内部パスへのリダイレクト
redirect(conn, to: "/dashboard")

# 外部URLへのリダイレクト
redirect(conn, external: "https://example.com")

# パイプラインの即時停止(後続のplug実行をブロック)
conn
|> put_status(401)
|> text("Unauthorized")
|> halt()

ヘッダーとCookieの操作(Modifying Headers & Cookies)

# レスポンスヘッダー
conn
|> put_resp_header("x-frame-options", "DENY")
|> put_resp_content_type("application/pdf")

# Cookie の設定と削除
conn
|> put_resp_cookie("session_id", "xyz", http_only: true, secure: true)
|> delete_resp_cookie("remember_token")

関連リファレンス

関連テーマ