빠른 참조

Phoenix Plug.Conn 치트시트

Phoenix의 Plug.Conn 핵심 참조 가이드: 요청 파라미터 조회, 응답 헤더 설정, 쿠키, 리다이렉트 및 파이프라인 중단(halt).

· 게시일

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")

관련 참조 문서

관련 주제