13장: 종합 실전: TODO 앱 처음부터 끝까지
전체 목차 · 이전: 12장: 테스트: httptest로 핸들러 검증 · 다음: 맺음말
이 책에서 다진 모든 도구를 하나로 모읍니다 — 3장의 templ 컴포넌트, 7장의 레이아웃, 8장의 SQLite, 10장의 세션 인증, 5장의 OOB 스왑. 로그인한 사용자만 자신의 할 일 목록을 보고, 추가·완료 토글·삭제가 모두 페이지 새로고침 없이 일어나는 작은 앱을 처음부터 조립합니다.
데이터 모델: 사용자와 할 일
8장의 스키마에 users 테이블과, 각 할 일이 어느 사용자의 것인지 나타내는 `user_id`를 추가합니다.
package main
import (
"database/sql"
"log"
_ "modernc.org/sqlite"
)
type User struct {
ID int64
Username string
PasswordHash string
}
type Todo struct {
ID int64
UserID int64
Text string
Done bool
}
func openDB(path string) *sql.DB {
db, err := sql.Open("sqlite", path)
if err != nil {
log.Fatal(err)
}
schema := `
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS todos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
text TEXT NOT NULL,
done BOOLEAN NOT NULL DEFAULT 0
);`
if _, err := db.Exec(schema); err != nil {
log.Fatal(err)
}
return db
}할 일을 다루는 모든 쿼리에 `WHERE user_id = ?`를 반드시 포함시킵니다 — 이걸 빠뜨리면 사용자 A가 사용자 B의 할 일을 보거나 지울 수 있게 되는 심각한 보안 결함이 됩니다.
func insertTodo(db *sql.DB, userID int64, text string) (Todo, error) {
res, err := db.Exec(`INSERT INTO todos (user_id, text, done) VALUES (?, ?, 0)`, userID, text)
if err != nil {
return Todo{}, err
}
id, _ := res.LastInsertId()
return Todo{ID: id, UserID: userID, Text: text, Done: false}, nil
}
func listTodos(db *sql.DB, userID int64) ([]Todo, error) {
rows, err := db.Query(`SELECT id, user_id, text, done FROM todos WHERE user_id = ? ORDER BY id`, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var todos []Todo
for rows.Next() {
var t Todo
if err := rows.Scan(&t.ID, &t.UserID, &t.Text, &t.Done); err != nil {
return nil, err
}
todos = append(todos, t)
}
return todos, rows.Err()
}
func toggleTodo(db *sql.DB, userID, todoID int64) error {
_, err := db.Exec(`UPDATE todos SET done = NOT done WHERE id = ? AND user_id = ?`, todoID, userID)
return err
}
func deleteTodo(db *sql.DB, userID, todoID int64) error {
_, err := db.Exec(`DELETE FROM todos WHERE id = ? AND user_id = ?`, todoID, userID)
return err
}
func countPending(db *sql.DB, userID int64) int {
var n int
db.QueryRow(`SELECT COUNT(*) FROM todos WHERE user_id = ? AND done = 0`, userID).Scan(&n)
return n
}toggleTodo`와 `deleteTodo`도 `AND user_id = ?`를 조건에 포함시켜, 설령 다른 사용자의 할 일 ID를 어떻게든 알아내 요청을 보내더라도 `UPDATE/`DELETE`가 아무 행에도 적용되지 않도록 막습니다.
화면: 로그인 페이지와 할 일 목록
7장의 `Layout`으로 공통 뼈대를 잡고, 로그인 페이지와 할 일 목록 페이지를 각각 구성합니다.
package main
import "fmt"
templ Layout(title string) {
<html>
<head>
<title>{ title }</title>
<script src="https://unpkg.com/htmx.org@2.0.3"></script>
</head>
<body>
{ children... }
</body>
</html>
}
templ LoginPage(errorMsg string) {
@Layout("로그인") {
<h1>로그인</h1>
if errorMsg != "" {
<p class="error">{ errorMsg }</p>
}
<form method="post" action="/login">
<input type="text" name="username" placeholder="아이디"/>
<input type="password" name="password" placeholder="비밀번호"/>
<button type="submit">로그인</button>
</form>
}
}
templ TodoPage(todos []Todo, pending int) {
@Layout("할 일 목록") {
<h1>할 일 목록</h1>
<p>미완료 <span id="pending-count">{ fmt.Sprint(pending) }</span>개</p>
<form hx-post="/todos" hx-target="#todo-list" hx-swap="beforeend">
<input type="text" name="text"/>
<button type="submit">추가</button>
</form>
<ul id="todo-list">
for _, t := range todos {
@TodoItem(t)
}
</ul>
<form method="post" action="/logout"><button type="submit">로그아웃</button></form>
}
}로그인 폼은 htmx 없이 평범한 `<form method="post">`를 씁니다 — 로그인은 성공하면 전체 페이지가 바뀌어야 하는(할 일 목록 페이지로 이동) 경우라, 부분 갱신보다 일반적인 폼 제출과 리다이렉트가 더 자연스럽습니다. 반면 할 일 추가/토글/삭제는 페이지 안에서 일부만 바뀌면 되므로 htmx를 씁니다.
할 일 항목: 체크박스와 삭제 버튼
templ TodoItem(t Todo) {
<li id={ fmt.Sprintf("todo-%d", t.ID) }>
<input type="checkbox"
checked?={ t.Done }
hx-post={ fmt.Sprintf("/todos/%d/toggle", t.ID) }
hx-target={ fmt.Sprintf("#todo-%d", t.ID) }
hx-swap="outerHTML"
/>
if t.Done {
<s>{ t.Text }</s>
} else {
{ t.Text }
}
<button
hx-delete={ fmt.Sprintf("/todos/%d", t.ID) }
hx-target={ fmt.Sprintf("#todo-%d", t.ID) }
hx-swap="delete"
>삭제</button>
</li>
}
templ TodoItemWithCount(t Todo, pending int) {
@TodoItem(t)
<span id="pending-count" hx-swap-oob="true">{ fmt.Sprint(pending) }</span>
}
templ PendingCountOOB(pending int) {
<span id="pending-count" hx-swap-oob="true">{ fmt.Sprint(pending) }</span>
}checked?={ t.Done }`는 templ의 조건부 불리언 속성 문법입니다 — `t.Done`이 참이면 `checked 속성 자체가 추가되고, 거짓이면 속성이 아예 나타나지 않습니다(`checked="false"`처럼 잘못된 형태가 아니라, HTML 표준대로 속성 존재 여부로 표현됩니다). `TodoItemWithCount`는 5장의 OOB 스왑 패턴 그대로, 항목 하나(추가되거나 토글된)와 미완료 개수 카운터를 한 응답에 함께 담습니다.
라우팅: 인증과 CRUD를 하나로 묶기
package main
import (
"context"
"net/http"
"strconv"
)
func main() {
db := openDB("todo.db")
defer db.Close()
store := NewSessionStore()
mux := http.NewServeMux()
mux.HandleFunc("GET /login", func(w http.ResponseWriter, r *http.Request) {
LoginPage("").Render(context.Background(), w)
})
mux.HandleFunc("POST /login", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
user, ok := findUserByUsername(db, r.FormValue("username"))
if !ok || !checkPassword(user.PasswordHash, r.FormValue("password")) {
LoginPage("아이디 또는 비밀번호가 올바르지 않습니다.").Render(context.Background(), w)
return
}
sid := store.Create(user.ID)
setSessionCookie(w, sid)
http.Redirect(w, r, "/", http.StatusSeeOther)
})
mux.HandleFunc("POST /logout", func(w http.ResponseWriter, r *http.Request) {
if cookie, err := r.Cookie(sessionCookieName); err == nil {
store.Destroy(cookie.Value)
}
http.Redirect(w, r, "/login", http.StatusSeeOther)
})
mux.HandleFunc("GET /", requireAuth(store, func(w http.ResponseWriter, r *http.Request) {
uid, _ := currentUserID(r, store)
todos, _ := listTodos(db, uid)
TodoPage(todos, countPending(db, uid)).Render(context.Background(), w)
}))
mux.HandleFunc("POST /todos", requireAuth(store, func(w http.ResponseWriter, r *http.Request) {
uid, _ := currentUserID(r, store)
r.ParseForm()
todo, err := insertTodo(db, uid, r.FormValue("text"))
if err != nil {
http.Error(w, "저장 실패", http.StatusInternalServerError)
return
}
TodoItemWithCount(todo, countPending(db, uid)).Render(context.Background(), w)
}))
mux.HandleFunc("POST /todos/{id}/toggle", requireAuth(store, func(w http.ResponseWriter, r *http.Request) {
uid, _ := currentUserID(r, store)
id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64)
toggleTodo(db, uid, id)
todos, _ := listTodos(db, uid)
var updated Todo
for _, t := range todos {
if t.ID == id {
updated = t
}
}
TodoItemWithCount(updated, countPending(db, uid)).Render(context.Background(), w)
}))
mux.HandleFunc("DELETE /todos/{id}", requireAuth(store, func(w http.ResponseWriter, r *http.Request) {
uid, _ := currentUserID(r, store)
id, _ := strconv.ParseInt(r.PathValue("id"), 10, 64)
deleteTodo(db, uid, id)
PendingCountOOB(countPending(db, uid)).Render(context.Background(), w)
}))
http.ListenAndServe(":8080", mux)
}모든 할 일 관련 라우트가 10장의 requireAuth`로 감싸져 있습니다 — 로그인하지 않은 채 `/todos`에 직접 요청을 보내도 세션이 없으면 로그인 페이지로 리다이렉트됩니다. `DELETE /todos/{id}`처럼 2장에서 배운 메서드 기반 라우팅이, 5장의 `hx-swap="delete"(응답 본문이 필요 없는)와 자연스럽게 맞물립니다.
처음부터 끝까지: curl로 전체 흐름 검증
JAR=/tmp/todoapp_cookies.txt
echo "-- 미로그인 접근 --"
curl -s -o /dev/null -w "%{http_code} %{redirect_url}\n" "http://localhost:8080/"
echo "-- 로그인 --"
curl -s -c $JAR -b $JAR -o /dev/null -w "%{http_code}\n" -X POST "http://localhost:8080/login" \
--data-urlencode "username=minjun" --data-urlencode "password=pass1234"
echo "-- 항목 추가 --"
curl -s -c $JAR -b $JAR -X POST "http://localhost:8080/todos" -H "HX-Request: true" \
--data-urlencode "text=우유 사기"
echo "-- 완료 토글 --"
curl -s -c $JAR -b $JAR -X POST "http://localhost:8080/todos/1/toggle" -H "HX-Request: true"
echo "-- 삭제 --"
curl -s -c $JAR -b $JAR -X DELETE "http://localhost:8080/todos/1" -H "HX-Request: true"-- 미로그인 접근 --
303 http://localhost:8080/login
-- 로그인 --
303
-- 항목 추가 --
<li id="todo-1"><input type="checkbox" hx-post="/todos/1/toggle" hx-target="#todo-1" hx-swap="outerHTML">
우유 사기 <button hx-delete="/todos/1" hx-target="#todo-1" hx-swap="delete">삭제</button></li>
<span id="pending-count" hx-swap-oob="true">1</span>
-- 완료 토글 --
<li id="todo-1"><input type="checkbox" checked hx-post="/todos/1/toggle" hx-target="#todo-1" hx-swap="outerHTML">
<s>우유 사기</s> <button hx-delete="/todos/1" hx-target="#todo-1" hx-swap="delete">삭제</button></li>
<span id="pending-count" hx-swap-oob="true">0</span>
-- 삭제 --
<span id="pending-count" hx-swap-oob="true">0</span>다섯 단계 모두 이 책에서 다진 도구들이 정확히 예상대로 맞물렸습니다. 미로그인 접근은 303`으로 `/login`으로 리다이렉트되고(10장), 로그인 후 항목을 추가하면 새 `<li>`와 갱신된 카운터가 함께 옵니다(5장의 OOB 스왑). 완료 토글은 체크박스에 `checked`가 붙고 텍스트가 `<s>(취소선)로 바뀌면서 카운터가 1`에서 `0`으로 줄어듭니다(7장의 조건부 렌더링). 삭제는 본문에 `<li>`에 대한 내용 없이 카운터만 담아 응답하고, `hx-swap="delete"`가 `<li> 자체를 화면에서 제거합니다(5장).
직접 해보기
12장에서 배운
httptest`로, 이 장의 `/todos핸들러가 로그인하지 않은 요청에는303`을, 로그인한 요청에는 새 할 일이 포함된 `200응답을 주는지 검증하는 테스트를 작성해보세요. 10장의requireAuth테스트와 12장의 폼 데이터 테스트를 그대로 조합하면 됩니다.
해답 보기
func mustHash(pw string) string {
h, err := hashPassword(pw)
if err != nil {
panic(err)
}
return h
}
func TestAddTodoRequiresAuth(t *testing.T) {
db := openDB("/tmp/test_todo_app.db")
defer db.Close()
store := NewSessionStore()
user, _ := createUser(db, "tester", mustHash("pw"))
handler := requireAuth(store, func(w http.ResponseWriter, r *http.Request) {
uid, _ := currentUserID(r, store)
r.ParseForm()
todo, _ := insertTodo(db, uid, r.FormValue("text"))
w.WriteHeader(http.StatusOK)
TodoItemWithCount(todo, countPending(db, uid)).Render(r.Context(), w)
})
t.Run("미로그인 -> 303", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/todos", strings.NewReader("text=test"))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusSeeOther {
t.Errorf("status = %d, want %d", rec.Code, http.StatusSeeOther)
}
})
t.Run("로그인 -> 200과 새 항목", func(t *testing.T) {
sid := store.Create(user.ID)
req := httptest.NewRequest(http.MethodPost, "/todos", strings.NewReader("text=우유 사기"))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: sid})
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("status = %d, want %d", rec.Code, http.StatusOK)
}
if !strings.Contains(rec.Body.String(), "우유 사기") {
t.Errorf("body missing new todo: %s", rec.Body.String())
}
})
}두 서브테스트가 정확히 12장의 패턴(httptest.NewRequest/NewRecorder)과 10장의 패턴(`req.AddCookie`로 세션 흉내)을 그대로 조합한 것입니다 — 이 책에서 각 장마다 익힌 조각들이, 실제 기능을 테스트할 때는 서로 독립적인 지식이 아니라 함께 조립해서 쓰는 도구라는 걸 보여줍니다.
요약
사용자별 데이터를 다룰 때는 모든 쿼리에
user_id조건을 반드시 포함시켜, 다른 사용자의 데이터에 접근하거나 변경할 수 없도록 막아야 합니다.로그인처럼 전체 페이지 전환이 자연스러운 경우엔 평범한 폼 제출을, 목록 내 항목 추가/토글/삭제처럼 부분 갱신이 자연스러운 경우엔 htmx를 각각 적재적소에 씁니다.
checked?={ … }같은 templ의 조건부 속성 문법으로, 상태에 따라 HTML 속성 자체의 존재 여부가 달라지는 화면을 표현합니다.curl로 로그인부터 추가·토글·삭제까지 전체 흐름을 검증해, 이 책의 각 장에서 배운 도구들이 실제로 하나의 앱 안에서 정확히 맞물려 동작한다는 것을 확인했습니다.
이 책의 마지막 장에서는 지금까지의 여정을 돌아보고, 이 책이 다루지 않은 것과 다음 단계를 정리합니다.