في إطار عمل Phoenix للغة Elixir، تمثل بنية Plug.Conn كلاً من طلب HTTP الوارد واستجابة HTTP الصادرة كهيكل بيانات غير قابل للتغيير يتم تحويله عبر طبقات 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}
# الوصول إلى ترويسات الطلب
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")
# إعادة توجيه خارجية
redirect(conn, external: "https://example.com")
# إيقاف مسار التدفق فورا (يمنع تنفيذ الـ plugs اللاحقة)
conn
|> put_status(401)
|> text("Unauthorized")
|> halt()
تعديل الترويسات وملفات تعريف الارتباط (Headers & Cookies)
# ترويسات الاستجابة
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")