Elixir의 Phoenix 프레임워크에서 Plug.Conn은 HTTP 요청과 응답을 포괄하는 불변 데이터 구조체로, Plug 파이프라인을 거치며 단계적으로 변환됩니다.
수신된 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()
헤더 및 쿠키 조작 (Modifying Headers & Cookies)
# 응답 헤더
conn
|> put_resp_header("x-frame-options", "DENY")
|> put_resp_content_type("application/pdf")
# 쿠키 설정 및 삭제
conn
|> put_resp_cookie("session_id", "xyz", http_only: true, secure: true)
|> delete_resp_cookie("remember_token")