In Elixir's Phoenix framework, Plug.Conn represents both the incoming HTTP request and the outgoing HTTP response as an immutable data struct transformed through plugs.
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}
# Accessing headers
get_req_header(conn, "authorization") # => ["Bearer token_xyz"]
Sending HTTP Responses
# Send JSON response
conn
|> put_status(200)
|> json(%{status: "ok", count: 42})
# Send HTML response
conn
|> put_status(200)
|> html("<h1>Welcome</h1>")
# Send plain text
conn
|> put_status(404)
|> text("Not Found")
Redirects & Flow Control
# Local redirect
redirect(conn, to: "/dashboard")
# External redirect
redirect(conn, external: "https://example.com")
# Halt pipeline execution (stops further plugs from executing)
conn
|> put_status(401)
|> text("Unauthorized")
|> halt()
Modifying Headers & Cookies
# Response headers
conn
|> put_resp_header("x-frame-options", "DENY")
|> put_resp_content_type("application/pdf")
# Cookies
conn
|> put_resp_cookie("session_id", "xyz", http_only: true, secure: true)
|> delete_resp_cookie("remember_token")