라우팅, 컨트롤러 및 플러그
경로를 정의하고 컨트롤러 동작을 구현하며, 모듈식이고 재사용 가능한 요청 파이프라인을 구축하기 위해 플러그를 사용합니다.
라우팅, 컨트롤러 및 플러그은(는) CoddyKit의 무료 Elixir & Phoenix: Scalable Backend Development 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Elixir & Phoenix: Scalable Backend Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Mapping Your Web Requests
Welcome to routing in Phoenix! Think of routing as your application's traffic controller. When a user visits a URL, the router determines which part of your code should handle that request.
It's how Phoenix connects an incoming web address (like /users) to a specific function in your application.
The `router.ex` File
In Phoenix, all your routes are defined in the lib/my_app_web/router.ex file. This file uses special macros to declare how different HTTP methods (GET, POST, PUT, DELETE) map to your application's logic.
You'll often see routes grouped into scopes and processed by pipelines, which apply common behaviors.
Defining a Simple Route
Let's look at how a basic route is defined. Here, a GET request to the root path / is mapped to the index function within PageController.
Notice the pipe_through :browser which applies a set of common behaviors to browser requests.
defmodule MyPhoenixAppWeb.Router do
use MyPhoenixAppWeb, :router
pipeline :browser do
plug :accepts, ["html"]
# ... other plugs for sessions, security, etc.
end
scope "/", MyPhoenixAppWeb do
pipe_through :browser
# Maps GET / to MyPhoenixAppWeb.PageController.index
get "/", PageController, :index
# Maps GET /hello to MyPhoenixAppWeb.PageController.hello
get "/hello", PageController, :hello
end
endControllers: Handling Requests
Once the router directs a request, a controller takes over. Controllers are Elixir modules that contain actions (functions) responsible for handling specific requests.
Their main job is to:
- Receive request parameters.
- Perform necessary business logic (e.g., fetch data).
- Prepare a response, often by rendering a template.
Your First Controller Action
Controller actions are just functions that accept two arguments: conn (the connection struct) and params (request parameters).
Here's a simple PageController with an index action that renders an index.html template.
defmodule MyPhoenixAppWeb.PageController do
use MyPhoenixAppWeb, :controller
# This action handles requests for the root path "/"
def index(conn, _params) do
# The render function looks for a template like page/index.html.heex
render(conn, "index.html")
end
# This action handles requests for "/hello"
def hello(conn, _params) do
text(conn, "Hello from Phoenix!")
end
endPath Helpers: Generating URLs
Instead of hardcoding URLs in your templates or code, Phoenix provides path helpers. These are functions that generate URLs based on your defined routes.
Using path helpers makes your links robust. If you change a route's path, you only update it in router.ex, and all generated links will automatically update.
For example, ~p"/" generates the root path.
Plugs: Request Middleware
Plugs are composable functions or modules that process the Plug.Conn (connection) struct. They act like middleware, allowing you to intercept and modify requests before they reach a controller, or modify responses after they leave.
Think of them as a series of steps a request goes through. Each plug can transform the request (or halt it) and pass it to the next plug in the pipeline.
Creating a Custom Plug
Plugs are simple Elixir modules implementing the init/1 and call/2 functions. init/1 is for configuration, and call/2 does the actual work.
Here's a plug that logs the request path and adds a custom header to the response:
defmodule MyPhoenixAppWeb.Plugs.MyLogger do
import Plug.Conn
def init(opts), do: opts
def call(conn, _opts) do
IO.puts("Request received for path: #{conn.request_path}")
put_resp_header(conn, "X-Custom-Header", "Hello from Plug!")
end
endUsing a Custom Plug
To use your custom plug, you add it to a pipeline in your router.ex file. All requests passing through that pipeline will then be processed by your plug.
For example, adding plug MyPhoenixAppWeb.Plugs.MyLogger to the :browser pipeline means every browser request will trigger this plug.
- Plug.Parsers: Parses request bodies (JSON, forms).
- Plug.Logger: Logs request details.
- Plug.Static: Serves static assets like CSS/JS.
Quick Check: Phoenix Request Flow
Let's test your understanding of how Phoenix handles web requests.
Recap: Routing, Controllers, Plugs
In this lesson, you've learned the core components that handle web requests in Phoenix:
- Routes (in
router.ex) map incoming URLs to controller actions. - Controllers contain actions (functions) that execute business logic and prepare responses.
- Plugs are reusable components that process the request connection (
Plug.Conn) in a pipeline, before or after the controller.
Together, these form a powerful and flexible system for building web applications.
자주 묻는 질문
“라우팅, 컨트롤러 및 플러그” 강의는 무료인가요?
네 — “라우팅, 컨트롤러 및 플러그” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Elixir & Phoenix: Scalable Backend Development 강의 전체를 잠금 해제할 수 있습니다. Elixir & Phoenix: Scalable Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“라우팅, 컨트롤러 및 플러그”에서 뭘 배우나요?
경로를 정의하고 컨트롤러 동작을 구현하며, 모듈식이고 재사용 가능한 요청 파이프라인을 구축하기 위해 플러그를 사용합니다. 브라우저에서 직접 실행하는 실습 코드로 Elixir & Phoenix: Scalable Backend Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Elixir & Phoenix: Scalable Backend Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Elixir & Phoenix: Scalable Backend Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“라우팅, 컨트롤러 및 플러그” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Elixir & Phoenix: Scalable Backend Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Elixir & Phoenix: Scalable Backend Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.