-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
204 lines (185 loc) · 6.16 KB
/
handler.go
File metadata and controls
204 lines (185 loc) · 6.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package main
import (
"encoding/json"
"html/template"
"log/slog"
"net/http"
"strings"
"time"
)
// responseWriter はステータスコードを記録するためのラッパー。
type responseWriter struct {
http.ResponseWriter
statusCode int
}
func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
}
// requestLogger はリクエストのメソッド・パス・ステータス・所要時間をログ出力するミドルウェア。
func requestLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rw := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}
next.ServeHTTP(rw, r)
slog.Info("リクエスト処理",
"method", r.Method,
"path", r.URL.Path,
"status", rw.statusCode,
"duration", time.Since(start).String(),
"remote", r.RemoteAddr,
)
})
}
// startTime はサーバー起動時刻を記録する。
var startTime = time.Now()
var tmpl = template.Must(template.New("").Funcs(template.FuncMap{
"progress": func(items []*Item) int {
if len(items) == 0 {
return 0
}
done := 0
for _, it := range items {
if it.Prepared {
done++
}
}
return done * 100 / len(items)
},
}).ParseGlob("templates/*.html"))
func registerRoutes(mux *http.ServeMux, store *Store) {
mux.HandleFunc("GET /health", handleHealth)
mux.HandleFunc("GET /", handleIndex)
mux.HandleFunc("POST /lists", handleCreateList(store))
mux.HandleFunc("GET /lists/{token}", handleShowList(store))
mux.HandleFunc("POST /lists/{token}/items", handleAddItem(store))
mux.HandleFunc("POST /lists/{token}/items/{id}/toggle-prepared", handleTogglePrepared(store))
mux.HandleFunc("POST /lists/{token}/items/{id}/toggle-required", handleToggleRequired(store))
mux.HandleFunc("POST /lists/{token}/items/{id}/assignee", handleUpdateAssignee(store))
mux.HandleFunc("POST /lists/{token}/items/{id}/delete", handleDeleteItem(store))
mux.HandleFunc("POST /lists/{token}/delete", handleDeleteList(store))
}
func handleHealth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{ //nolint:errcheck
"status": "ok",
"service": "bringit",
"uptime": time.Since(startTime).Round(time.Second).String(),
"timestamp": time.Now().UTC().Format(time.RFC3339),
})
}
func handleIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
if err := tmpl.ExecuteTemplate(w, "index.html", nil); err != nil {
slog.Error("テンプレート描画エラー", "template", "index.html", "error", err)
http.Error(w, "テンプレートの描画に失敗しました", http.StatusInternalServerError)
}
}
// 入力値の最大文字数制限。
const (
maxTitleLen = 100
maxDescriptionLen = 500
maxItemNameLen = 100
maxAssigneeLen = 50
)
// truncateRunes は文字列を最大 n ルーン以内に切り詰める。
func truncateRunes(s string, n int) string {
runes := []rune(s)
if len(runes) > n {
return string(runes[:n])
}
return s
}
func handleCreateList(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
title := strings.TrimSpace(r.FormValue("title"))
if title == "" {
http.Error(w, "タイトルは必須です", http.StatusBadRequest)
return
}
title = truncateRunes(title, maxTitleLen)
desc := truncateRunes(strings.TrimSpace(r.FormValue("description")), maxDescriptionLen)
l := store.CreateList(title, desc)
http.Redirect(w, r, "/lists/"+l.ShareToken, http.StatusSeeOther)
}
}
func handleShowList(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.PathValue("token")
l := store.GetList(token)
if l == nil {
http.NotFound(w, r)
return
}
data := map[string]any{
"List": l,
"ShareURL": buildShareURL(r, l.ShareToken),
}
if err := tmpl.ExecuteTemplate(w, "list.html", data); err != nil {
slog.Error("テンプレート描画エラー", "template", "list.html", "error", err)
http.Error(w, "テンプレートの描画に失敗しました", http.StatusInternalServerError)
}
}
}
func handleAddItem(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.PathValue("token")
name := strings.TrimSpace(r.FormValue("name"))
if name == "" {
http.Redirect(w, r, "/lists/"+token, http.StatusSeeOther)
return
}
name = truncateRunes(name, maxItemNameLen)
assignee := truncateRunes(strings.TrimSpace(r.FormValue("assignee")), maxAssigneeLen)
required := r.FormValue("required") == "on"
store.AddItem(token, name, assignee, required)
http.Redirect(w, r, "/lists/"+token, http.StatusSeeOther)
}
}
func handleTogglePrepared(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.PathValue("token")
id := r.PathValue("id")
store.TogglePrepared(token, id)
http.Redirect(w, r, "/lists/"+token, http.StatusSeeOther)
}
}
func handleToggleRequired(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.PathValue("token")
id := r.PathValue("id")
store.ToggleRequired(token, id)
http.Redirect(w, r, "/lists/"+token, http.StatusSeeOther)
}
}
func handleUpdateAssignee(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.PathValue("token")
id := r.PathValue("id")
assignee := truncateRunes(strings.TrimSpace(r.FormValue("assignee")), maxAssigneeLen)
store.UpdateAssignee(token, id, assignee)
http.Redirect(w, r, "/lists/"+token, http.StatusSeeOther)
}
}
func handleDeleteItem(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.PathValue("token")
id := r.PathValue("id")
store.DeleteItem(token, id)
http.Redirect(w, r, "/lists/"+token, http.StatusSeeOther)
}
}
func handleDeleteList(store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.PathValue("token")
if !store.DeleteList(token) {
http.NotFound(w, r)
return
}
http.Redirect(w, r, "/", http.StatusSeeOther)
}
}