4장. 핸들러와 응답 — 요청을 처리하고 결과를 반환하기
약 23분 읽기
4장. 핸들러와 응답 — 요청을 처리하고 결과를 반환하기
핸들러는 요청을 받아 처리하고 응답을 반환하는 함수입니다. Axum에서 핸들러는 async 함수이며, 특별한 어노테이션이 필요 없습니다. 이 장에서는 핸들러를 작성하는 방법과, 다양한 응답 타입을 반환하는 방법을 배웁니다.
4.1 핸들러란?
Axum에서 핸들러는 Handler 트레이트를 구현하는 모든 타입입니다. 다행히 대부분의 async 함수는 자동으로 Handler가 됩니다. 핸들러 함수의 규칙은 다음과 같습니다.
- async fn이어야 합니다 (또는 Future를 반환해야 합니다).
- 매개변수는 FromRequest 또는 FromRequestParts를 구현해야 합니다.
- 반환 타입은 IntoResponse를 구현해야 합니다.
- 마지막 매개변수만이 FromRequest(요청 본문을 읽는)가 될 수 있습니다.
// 가장 단순한 핸들러: 매개변수 없음, &'static str 반환
async fn hello() -> &'static str {
"Hello!"
}
// 매개변수가 있는 핸들러: Path 추출자
async fn get_user(Path(id): Path<u64>) -> String {
format!("사용자 {}", id)
}
// 여러 매개변수를 가진 핸들러
async fn update_user(
State(db): State<Db>, // 상태
Path(id): Path<u64>, // 경로 매개변수
Json(input): Json<UpdateUser>, // 요청 본문 (마지막!)
) -> Json<User> {
let user = db.update_user(id, input).await;
Json(user)
}
4.2 IntoResponse 트레이트
핸들러의 반환 타입은 IntoResponse 트레이트를 구현해야 합니다. 이 트레이트는 타입을 HTTP 응답으로 변환하는 방법을 정의합니다. Axum은 많은 타입에 대해 IntoResponse를 미리 구현해 두었습니다.
| 타입 | Content-Type | 설명 |
|---|---|---|
| &’static str | text/plain | 정적 문자열 |
| String | text/plain | 동적 문자열 |
| &’static [u8] | application/octet-stream | 정적 바이트 |
| Vec<u8> | application/octet-stream | 동적 바이트 |
| Json<T> | application/json | JSON 직렬화 |
| Html<T> | text/html | HTML 응답 |
| Form<T> | application/x-www-form-urlencoded | 폼 데이터 |
| Redirect | Location 헤더 | 리다이렉트 |
| StatusCode | (본문 없음) | 상태 코드만 |
| (StatusCode, T) | T에 따라 | 상태 코드 + 본문 |
| Response | 직접 지정 | 완전한 커스텀 응답 |
4.2.1 문자열 응답
use axum::response::IntoResponse;
// &'static str — 가장 단순한 응답
async fn plain_text() -> &'static str {
"안녕하세요!"
}
// String — 동적으로 생성한 문자열
async fn greeting(Path(name): Path<String>) -> String {
format!("안녕하세요, {}님!", name)
}
// 명시적으로 Content-Type을 지정하려면 튜플 사용
async fn csv_data() -> impl IntoResponse {
(
// 상태 코드
axum::http::StatusCode::OK,
// 헤더들
[(
axum::http::header::CONTENT_TYPE,
"text/csv; charset=utf-8",
)],
// 본문
"name,age\n홍길동,30\n김철수,25",
)
}
4.2.2 JSON 응답
JSON은 현대 웹 API의 표준 응답 형식입니다. Axum의 Json<T>를 사용하면, Serialize를 구현한 타입을 자동으로 JSON으로 직렬화하여 응답합니다.
use axum::{response::Json, http::StatusCode};
use serde::Serialize;
// 응답으로 반환할 데이터 구조체
// serde::Serialize를 파생해야 Json으로 변환할 수 있습니다.
#[derive(Serialize)]
struct UserResponse {
id: u64,
name: String,
email: String,
}
// Json<UserResponse>를 반환하면 자동으로 JSON 응답이 됩니다.
async fn get_user() -> Json<UserResponse> {
Json(UserResponse {
id: 1,
name: "홍길동".to_string(),
email: "hong@example.com".to_string(),
})
}
// 상태 코드와 함께 반환하려면 튜플 사용
async fn create_user() -> (StatusCode, Json<UserResponse>) {
(
StatusCode::CREATED, // 201 Created
Json(UserResponse {
id: 2,
name: "김철수".to_string(),
email: "kim@example.com".to_string(),
}),
)
}
// 생성된 JSON 응답:
// HTTP/1.1 201 Created
// content-type: application/json
// {"id":2,"name":"김철수","email":"kim@example.com"}
4.2.3 HTML 응답
웹 페이지를 반환할 때는 Html<T>를 사용합니다. Content-Type이 text/html로 설정됩니다. 템플릿 엔진과 함께 사용하면 동적 HTML을 생성할 수 있습니다.
use axum::response::Html;
async fn homepage() -> Html<String> {
let html = format!(r#"
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>내 홈페이지</title>
</head>
<body>
<h1>환영합니다!</h1>
<p>Axum으로 만든 웹페이지입니다.</p>
</body>
</html>
"#);
Html(html)
}
4.2.4 리다이렉트
Redirect 타입으로 HTTP 리다이렉트 응답을 보낼 수 있습니다. 영구(301)와 임시(307) 리다이렉트를 지원합니다.
use axum::response::Redirect;
// 영구 리다이렉트 (301 Moved Permanently)
// 브라우저가 이 URL을 캐시하므로, 정말 영구적인 변경에만 사용하세요.
async fn old_url() -> Redirect {
Redirect::permanent("/new-url")
}
// 임시 리다이렉트 (307 Temporary Redirect)
// 메서드를 유지합니다 (POST는 POST로 리다이렉트).
async fn login_required() -> Redirect {
Redirect::temporary("/login")
}
// 외부 URL로도 리다이렉트할 수 있습니다.
async fn external_link() -> Redirect {
Redirect::to("https://example.com")
}
4.2.5 상태 코드만 반환
use axum::http::StatusCode;
async fn health() -> StatusCode {
StatusCode::OK // 200
}
async fn not_found() -> StatusCode {
StatusCode::NOT_FOUND // 404
}
async fn no_content() -> StatusCode {
StatusCode::NO_CONTENT // 204 (본문 없음)
}
4.3 튜플 응답 — 상태, 헤더, 본문 조합
응답의 상태 코드, 헤더, 본문을 자유롭게 조합하려면 튜플을 사용합니다. 튜플의 각 요소가 순서대로 응답의 구성 요소가 됩니다.
use axum::{
http::{StatusCode, header, HeaderMap, HeaderName, HeaderValue},
response::IntoResponse,
Json,
};
use serde_json::json;
async fn custom_response() -> impl IntoResponse {
// 튜플 순서: (상태코드, 헤더, 본문)
// 헤더는 [(HeaderName, HeaderValue); N] 배열 또는 HeaderMap으로 전달합니다.
(
StatusCode::CREATED, // 201 Created
[
(header::CONTENT_TYPE, "application/json"),
(header::CACHE_CONTROL, "no-cache"),
("X-Custom-Header", "custom-value"), // 커스텀 헤더
],
Json(json!({
"success": true,
"message": "리소스가 생성되었습니다",
})),
)
}
// 헤더가 필요 없다면 생략 가능
async fn simple_with_status() -> impl IntoResponse {
(StatusCode::ACCEPTED, "요청이 접수되었습니다")
}
// 상태 코드만 필요하면 튜플 없이 StatusCode 단독 사용
async fn just_status() -> StatusCode {
StatusCode::NO_CONTENT
}
4.4 Result를 응답으로 사용
Rust의 Result<T, E> 타입도 IntoResponse를 구현합니다. Ok인 경우 T를 응답으로 반환하고, Err인 경우 E를 응답으로 변환합니다. 이는 에러 처리를 우아하게 만드는 핵심 기능입니다.
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use serde::Serialize;
// 커스텀 에러 타입 — IntoResponse를 구현해야 합니다.
enum AppError {
NotFound,
BadRequest(String),
Internal(String),
}
// 에러를 HTTP 응답으로 변환하는 구현입니다.
impl IntoResponse for AppError {
fn into_response(self) -> Response {
match self {
AppError::NotFound => (
StatusCode::NOT_FOUND,
"리소스를 찾을 수 없습니다",
).into_response(),
AppError::BadRequest(msg) => (
StatusCode::BAD_REQUEST,
msg,
).into_response(),
AppError::Internal(msg) => (
StatusCode::INTERNAL_SERVER_ERROR,
msg,
).into_response(),
}
}
}
// 핸들러에서 Result를 반환하면 ? 연산자로 에러를 전파할 수 있습니다.
#[derive(Serialize)]
struct User { id: u64, name: String }
async fn get_user(Path(id): Path<u64>) -> Result<Json<User>, AppError> {
// 데이터베이스에서 사용자를 찾습니다.
// 에러가 발생하면 ?가 자동으로 AppError로 변환하여 반환합니다.
let user = find_user(id).await
.ok_or(AppError::NotFound)?;
// 사용자 검증
if user.name.is_empty() {
return Err(AppError::BadRequest("이름이 비어 있습니다".into()));
}
Ok(Json(user))
}
async fn find_user(id: u64) -> Option<User> {
// 실제로는 데이터베이스 쿼리
Some(User { id, name: "홍길동".into() })
}
【중요】 Result를 응답으로 사용할 때는 에러 타입이 반드시 IntoResponse를 구현해야 합니다. 그렇지 않으면 컴파일 에러가 발생합니다. 에러 처리의 자세한 내용은 9장에서 다룹니다.
4.5 스트리밍 응답
대용량 데이터나 실시간 데이터를 전송할 때는 스트리밍 응답을 사용합니다. Axum은 Stream 형태의 응답을 지원합니다.
use axum::{
body::Body,
response::IntoResponse,
http::StatusCode,
};
use futures_util::stream::{self, StreamExt};
use std::time::Duration;
async fn stream_data() -> impl IntoResponse {
// 1초마다 메시지를 보내는 스트림
let stream = stream::iter(0..10)
.then(|i| async move {
tokio::time::sleep(Duration::from_secs(1)).await;
Ok::<_, std::io::Error>(format!("데이터 {}\n", i))
})
.map(|result| {
result.map(|chunk| chunk.into_bytes())
});
(
StatusCode::OK,
[("content-type", "text/plain")],
Body::from_stream(stream),
)
}
4.6 파일 다운로드 응답
파일을 다운로드시키려면 Content-Disposition 헤더를 설정하고 파일 내용을 본문으로 보냅니다.
use axum::{
body::Body,
http::{header, StatusCode, HeaderValue},
response::IntoResponse,
};
use tokio::fs::File;
use tokio_util::io::ReaderStream;
async fn download_file() -> impl IntoResponse {
// 파일을 열어 스트림으로 변환합니다.
let file = File::open("large_file.zip").await.unwrap();
let stream = ReaderStream::new(file);
let body = Body::from_stream(stream);
(
StatusCode::OK,
[
(header::CONTENT_TYPE, "application/zip"),
// attachment; filename="..." 헤더가 브라우저에게
// 이 응답을 파일로 저장하라고 알립니다.
(
header::CONTENT_DISPOSITION,
"attachment; filename=\"large_file.zip\"",
),
],
body,
)
}
4.7 커스텀 응답 구조체
반복되는 응답 패턴은 자체 구조체로 캡슐화하면 좋습니다. IntoResponse를 구현하여 재사용 가능한 응답 타입을 만들 수 있습니다.
use axum::{
http::{StatusCode, header},
response::{IntoResponse, Response},
};
use serde::Serialize;
// 표준화된 API 응답 래퍼
#[derive(Serialize)]
struct ApiResponse<T: Serialize> {
success: bool,
data: Option<T>,
error: Option<String>,
}
impl<T: Serialize> IntoResponse for ApiResponse<T> {
fn into_response(self) -> Response {
// 자기 자신을 JSON으로 직렬화합니다.
let body = serde_json::to_string(&self).unwrap();
(
StatusCode::OK,
[(header::CONTENT_TYPE, "application/json")],
body,
).into_response()
}
}
// 이제 핸들러에서 일관된 형식으로 응답할 수 있습니다.
async fn get_user() -> ApiResponse<User> {
ApiResponse {
success: true,
data: Some(User { id: 1, name: "홍길동".into() }),
error: None,
}
}
async fn fail() -> ApiResponse<User> {
ApiResponse {
success: false,
data: None,
error: Some("사용자를 찾을 수 없습니다".into()),
}
}
4.8 쿠키 설정
쿠키를 설정하려면 Set-Cookie 헤더를 사용합니다. axum-extra의 Cookie 타입을 사용하면 편리합니다.
// Cargo.toml: axum-extra = { version = "0.10", features = ["cookie"] }
use axum_extra::extract::cookie::{Cookie, SameSite};
use axum::response::{IntoResponse, Redirect};
async fn login() -> impl IntoResponse {
// 보안 쿠키 생성
let cookie = Cookie::build(("session_id", "abc123"))
.path("/") // 모든 경로에서 접근 가능
.secure(true) // HTTPS에서만 전송
.http_only(true) // JavaScript에서 접근 불가 (XSS 방어)
.same_site(SameSite::Lax)// CSRF 방어
.max_age(time::Duration::hours(24)); // 24시간 유효
// 쿠키와 함께 리다이렉트
(cookie, Redirect::to("/dashboard"))
}
// 쿠키 읽기
async fn dashboard(
cookies: axum_extra::extract::CookieJar,
) -> String {
let session_id = cookies.get("session_id")
.map(|c| c.value().to_string())
.unwrap_or_else(|| "로그인되지 않음".to_string());
format!("세션: {}", session_id)
}
4.9 요약
이 장에서는 핸들러를 작성하고 다양한 응답을 반환하는 방법을 배웠습니다. 핵심은 다음과 같습니다. 핸들러는 async 함수이며, 매개변수는 추출자, 반환 타입은 IntoResponse를 구현해야 합니다. Json<T>, Html<T>, Redirect, StatusCode 등이 자주 쓰이는 응답 타입입니다. 튜플로 상태 코드, 헤더, 본문을 자유롭게 조합할 수 있고, Result로 에러를 우아하게 처리할 수 있습니다. 스트리밍 응답, 파일 다운로드, 커스텀 응답 구조체, 쿠키 설정 등 실전적인 기법도 살펴봤습니다.
다음 장에서는 더 복잡한 핸들러 예제를 통해, 지금까지 배운 내용을 종합적으로 실습해 보겠습니다. 간단한 REST API를 단계적으로 구축하면서 실전 감각을 익히겠습니다.