learn-go/snippetbox/cmd/web/handlers.go

78 lines
1.5 KiB
Go
Raw Normal View History

2024-01-22 21:25:34 +00:00
package main
import (
2024-01-25 20:41:08 +00:00
"errors"
"fmt"
2024-01-22 21:25:34 +00:00
"net/http"
"strconv"
2024-01-25 20:41:08 +00:00
"snippetbox.chaosfem.tw/internal/models"
2024-01-22 21:25:34 +00:00
)
// home ...
func (app *application) home(w http.ResponseWriter, r *http.Request) {
2024-01-22 21:25:34 +00:00
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
2024-01-23 19:19:53 +00:00
2024-01-25 20:41:08 +00:00
snippets, err := app.snippets.Latest()
2024-01-23 19:19:53 +00:00
if err != nil {
app.serverError(w, r, err)
2024-01-23 19:19:53 +00:00
return
}
2024-01-25 22:08:58 +00:00
data := templateData{
Snippets: snippets,
}
2024-01-25 23:06:28 +00:00
app.render(w, r, http.StatusOK, "home.tmpl", data)
2024-01-22 21:25:34 +00:00
}
// snippetView ...
func (app *application) snippetView(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.URL.Query().Get("id"))
if err != nil || id < 1 {
app.notFound(w)
return
}
2024-01-25 20:41:08 +00:00
snippet, err := app.snippets.Get(id)
if err != nil || id < 1 {
if errors.Is(err, models.ErrNoRecord) {
app.notFound(w)
} else {
app.serverError(w, r, err)
}
return
}
2024-01-25 21:41:06 +00:00
data := templateData{
Snippet: snippet,
}
2024-01-25 23:06:28 +00:00
app.render(w, r, http.StatusOK, "view.tmpl", data)
2024-01-22 21:25:34 +00:00
}
// snippetCreate ...
func (app *application) snippetCreate(w http.ResponseWriter, r *http.Request) {
2024-01-22 21:25:34 +00:00
w.Header().Set("Allow", "POST")
if r.Method != http.MethodPost {
app.clientError(w, http.StatusMethodNotAllowed)
2024-01-22 21:25:34 +00:00
return
}
2024-01-25 20:41:08 +00:00
title := "0 snail"
content := "0 snail\nClimb Mount Fuji,\nBut slowly, slowly!\n\n - Kobayashi Issa"
expires := 7
id, err := app.snippets.Insert(title, content, expires)
if err != nil {
app.serverError(w, r, err)
return
}
http.Redirect(w, r, fmt.Sprintf("/snippet/view?id=%d", id), http.StatusSeeOther)
2024-01-22 21:25:34 +00:00
}