78 lines
1.5 KiB
Go
78 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"snippetbox.chaosfem.tw/internal/models"
|
|
)
|
|
|
|
// home ...
|
|
func (app *application) home(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/" {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
|
|
snippets, err := app.snippets.Latest()
|
|
if err != nil {
|
|
app.serverError(w, r, err)
|
|
return
|
|
}
|
|
|
|
data := templateData{
|
|
Snippets: snippets,
|
|
}
|
|
|
|
app.render(w, r, http.StatusOK, "home.tmpl", data)
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
data := templateData{
|
|
Snippet: snippet,
|
|
}
|
|
|
|
app.render(w, r, http.StatusOK, "view.tmpl", data)
|
|
}
|
|
|
|
// snippetCreate ...
|
|
func (app *application) snippetCreate(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Allow", "POST")
|
|
|
|
if r.Method != http.MethodPost {
|
|
app.clientError(w, http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
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)
|
|
}
|