Skip to content

Commit da5c4e4

Browse files
committed
Step-5 Refactor
- Move all templating code to its own function. - Handle non-existent pages in `viewHandler`.
1 parent ac8e261 commit da5c4e4

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

gowiki.go

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,19 @@ func loadPage(title string) (*Page, error) {
2626
return &Page{Title: title, Body: body}, nil
2727
}
2828

29+
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
30+
t, _ := template.ParseFiles(tmpl + ".html")
31+
t.Execute(w, p)
32+
}
33+
2934
func viewHandler(w http.ResponseWriter, r *http.Request) {
3035
title := r.URL.Path[len("/view/"):]
31-
p, _ := loadPage(title)
32-
t, _ := template.ParseFiles("view.html")
33-
t.Execute(w, p)
36+
p, err := loadPage(title)
37+
if err != nil {
38+
http.Redirect(w, r, "/edit/"+title, http.StatusFound)
39+
return
40+
}
41+
renderTemplate(w, "view", p)
3442
}
3543

3644
func editHandler(w http.ResponseWriter, r *http.Request) {
@@ -39,8 +47,7 @@ func editHandler(w http.ResponseWriter, r *http.Request) {
3947
if err != nil {
4048
p = &Page{Title: title}
4149
}
42-
t, _ := template.ParseFiles("edit.html")
43-
t.Execute(w, p)
50+
renderTemplate(w, "edit", p)
4451
}
4552

4653
func main() {

0 commit comments

Comments
 (0)