The Phoenix framework, built on the Elixir programming language, is a powerful tool for developing robust, high performance web applications. At the core of Phoenix's request handling lies the Conn struct. It is a central data structure that encapsulates the details of incoming requests and manages the flow of data throughout the application.
In this article, we will dive into the Conn struct and explore its key components, functions, and how it facilitates request handling in the Phoenix framework.
The Conn struct, short for connection, represents the connection context of an incoming HTTP request in a Phoenix application. It contains information about the request and response data, such as headers, parameters, cookies, session data, etc. By working with the Conn struct, developers can access and manipulate the request and response data during the request handling pipeline.
The Conn struct consists of various fields that provide access to different aspects of the request and response. Some of the important fields include method
(HTTP method), path_info
(requested path), params
(parameters), cookies
(request cookies), and resp_body
(response body). Understanding these fields enables developers to extract and modify relevant data during request processing.
The Phoenix framework offers a rich set of functions to manipulate the Conn struct at various stages of request handling. Developers can use functions like put_resp_header/3
to add or modify response headers, assign/3
to set or modify values in the assigns map, and redirect/2
to redirect the client to a new URL. These functions provide flexibility in customizing the application's behavior based on the request context.
The Conn struct plays a central role in the request handling pipeline of a Phoenix application. It travels through a series of plugs, which are modular units responsible for intercepting and modifying the Conn struct. Each plug performs a specific task, such as authentication, parameter parsing, session management, or error handling. By understanding the request handling pipeline and the flow of the Conn struct, developers can effectively handle and transform requests in a structured manner.
The Conn struct also plays a crucial role in testing and debugging Phoenix applications. During testing, developers can create mock Conn structs to simulate different request scenarios and assert the expected behavior. Additionally, printing the Conn struct using IO.inspect
aids in debugging by providing insights into the request details, headers, parameters, and more. Proper utilization of testing and debugging techniques with the Conn struct can enhance the development process and improve the overall quality of Phoenix applications.
This is a general output of the Conn struct when we run the IO.inspect()
function in the Phoenix controller. Take a look at all the fields of the Conn struct to understand it better.
conn: %Plug.Conn{adapter: {Plug.Cowboy.Conn, :...},assigns: %{},body_params: %{},cookies: %{"_test" => "F%2BFrm3XCCQRaMDzVDv4vp7TsOi7QQ%%2Fjp4EocjlyIoZtmFEcjQ%2BeVr8GQI3Kw7uIu7cL%%3D%3D--kT%--%3D%3D","_educative_key" => "SFMyNTY.g3QAAAABbQAAAAtfY3NyZl90b2tlbm0AAAAYc3ZQUUIwVXVkTU1YN1Q5c0R4RjNRb2h0.BhYjeDC_qnwKx7l0PuVyPjpElD3spCCyezOJq0suhFw","_test_key" => "SFMyNTY.g3QAAAABbQAAAAtfY3NyZl90b2tlbm0AAAAYLWdycV9mcUFDRW1ZYzg2anlCUnliN2Rf.NtTYGQewdcenD02YQEFYmGiFQUFEfrczbNo2u_29Sd0"},halted: false,host: "ed-4623107647602688.educative.run",method: "GET",owner: #PID<0.567.0>,params: %{},path_info: [],path_params: %{},port: 80,private: %{TestWeb.Router => {[], %{Plug.Swoosh.MailboxPreview => ["mailbox"]}},:before_send => [#Function<0.63721220/1 in Plug.CSRFProtection.call/2>,#Function<2.9022821/1 in Phoenix.Controller.fetch_flash/2>,#Function<0.323658/1 in Plug.Session.before_send/2>,#Function<0.20582249/1 in Plug.Telemetry.call/2>,#Function<1.44153958/1 in Phoenix.LiveReloader.before_send_inject_reloader/3>],:phoenix_action => :index,:phoenix_controller => TestWeb.PageController,:phoenix_endpoint => TestWeb.Endpoint,:phoenix_flash => %{},:phoenix_format => "html",:phoenix_layout => {TestWeb.LayoutView, :app},:phoenix_request_logger => {"request_logger", "request_logger"},:phoenix_root_layout => {TestWeb.LayoutView, :root},:phoenix_router => TestWeb.Router,:phoenix_view => TestWeb.PageView,:plug_session => %{"_csrf_token" => "-grq_fqACEmYc86jyBRyb7d_"},:plug_session_fetch => :done},query_params: %{},query_string: "",remote_ip: {10, 128, 0, 4},req_cookies: %{"_billsplit_initial_session" => "F%2BY5H%2FBT%2BfEn38FHsnojSgIZAN3nePi3Eu6pDYyXhpDU1YunV3UBVAAesYSsulxKzS715s3e8tvdjJij5i7GcZgGLVFusjAYMX29RuUqM8hAFF%2Frm3XCCQRaMDzVDv4vp7TsOi7YtxaklISQQ%2FDKxqP1Pt8f8GYxisch9u6k3Vy1e3h03eLJ2A0irvq22kq3%2Fjp4EocjlyIoZtmFEcjQ%2BeVr8GQI3Kw7uIu7cL%2BpBEdJn0o5M3IOWCZViggf12h2ju2jZEkn30aUgxc2Utj5dUL7xm0inc8Pz4026nGbk3tMoQ%3D%3D--kT%2FxXTjLCaN3GaFL--QYV4EYrBsgAsJ2trNhFvbg%3D%3D","_educative_key" => "SFMyNTY.g3QAAAABbQAAAAtfY3NyZl90b2tlbm0AAAAYc3ZQUUIwVXVkTU1YN1Q5c0R4RjNRb2h0.BhYjeDC_qnwKx7l0PuVyPjpElD3spCCyezOJq0suhFw","_test_key" => "SFMyNTY.g3QAAAABbQAAAAtfY3NyZl90b2tlbm0AAAAYLWdycV9mcUFDRW1ZYzg2anlCUnliN2Rf.NtTYGQewdcenD02YQEFYmGiFQUFEfrczbNo2u_29Sd0"},req_headers: [{"accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"},{"accept-encoding", "gzip, deflate, br"},{"accept-language", "en-GB,en-US;q=0.9,en;q=0.8"},{"cache-control", "max-age=0"},{"connection", "close"},{"cookie","_billsplit_initial_session=F%2BY5H%2FBT%2BfEn38FHsnojSgIZAN3nePi3Eu6pDYyXhpDU1YunV3UBVAAesYSsulxKzS715s3e8tvdjJij5i7GcZgGLVFusjAYMX29RuUqM8hAFF%2Frm3XCCQRaMDzVDv4vp7TsOi7YtxaklISQQ%2FDKxqP1Pt8f8GYxisch9u6k3Vy1e3h03eLJ2A0irvq22kq3%2Fjp4EocjlyIoZtmFEcjQ%2BeVr8GQI3Kw7uIu7cL%2BpBEdJn0o5M3IOWCZViggf12h2ju2jZEkn30aUgxc2Utj5dUL7xm0inc8Pz4026nGbk3tMoQ%3D%3D--kT%2FxXTjLCaN3GaFL--QYV4EYrBsgAsJ2trNhFvbg%3D%3D; _educative_key=SFMyNTY.g3QAAAABbQAAAAtfY3NyZl90b2tlbm0AAAAYc3ZQUUIwVXVkTU1YN1Q5c0R4RjNRb2h0.BhYjeDC_qnwKx7l0PuVyPjpElD3spCCyezOJq0suhFw; _test_key=SFMyNTY.g3QAAAABbQAAAAtfY3NyZl90b2tlbm0AAAAYLWdycV9mcUFDRW1ZYzg2anlCUnliN2Rf.NtTYGQewdcenD02YQEFYmGiFQUFEfrczbNo2u_29Sd0"},{"host", "ed-4623107647602688.educative.run"},{"referer", "https://ed-4623107647602688.educative.run/"},{"sec-ch-ua","\"Google Chrome\";v=\"113\", \"Chromium\";v=\"113\", \"Not-A.Brand\";v=\"24\""},{"sec-ch-ua-mobile", "?0"},{"sec-ch-ua-platform", "\"macOS\""},{"sec-fetch-dest", "document"},{"sec-fetch-mode", "navigate"},{"sec-fetch-site", "same-origin"},{"sec-fetch-user", "?1"},{"upgrade-insecure-requests", "1"},{"user-agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"}],request_path: "/",resp_body: nil,resp_cookies: %{},resp_headers: [{"cache-control", "max-age=0, private, must-revalidate"},{"x-request-id", "F2ZgTHBmAIZTynwAAAOR"},{"x-frame-options", "SAMEORIGIN"},{"x-xss-protection", "1; mode=block"},{"x-content-type-options", "nosniff"},{"x-download-options", "noopen"},{"x-permitted-cross-domain-policies", "none"},{"cross-origin-window-policy", "deny"}],scheme: :http,script_name: [],secret_key_base: :...,state: :unset,status: nil}
Execute the following application to get the abovementioned response in the terminal. Open the app UI by clicking on the link provided against “Your app can be found at”.
/* This file is for your main application css. */ @import "./phoenix.css"; /* Alerts and form errors */ .alert { padding: 15px; margin-bottom: 20px; border: 1px solid transparent; border-radius: 4px; } .alert-info { color: #31708f; background-color: #d9edf7; border-color: #bce8f1; } .alert-warning { color: #8a6d3b; background-color: #fcf8e3; border-color: #faebcc; } .alert-danger { color: #a94442; background-color: #f2dede; border-color: #ebccd1; } .alert p { margin-bottom: 0; } .alert:empty { display: none; } .invalid-feedback { color: #a94442; display: block; margin: -1rem 0 2rem; }
In lines 5–6: We have used the IO.inspect()
function to print the Conn struct once we open the browser after the successful execution of the application in the page_controller.ex
file.
The Conn struct lies at the heart of request handling in the Phoenix Framework. By understanding its structure, functions, and role in the request handling pipeline, developers gain powerful tools to process, manipulate, and respond to HTTP requests effectively. The versatility of the Conn struct allows for flexible customization and seamless integration with other Phoenix components, resulting in the development of robust and performant web applications.
Free Resources