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

72 lines
1.6 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
2024-01-26 06:01:12 +00:00
"github.com/julienschmidt/httprouter"
2024-01-25 20:41:08 +00:00
"snippetbox.chaosfem.tw/internal/models"
2024-01-22 21:25:34 +00:00
)
// home ...
2024-01-26 06:01:12 +00:00
func (app *application) home(w http.ResponseWriter, r *http.Request) {
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 23:43:07 +00:00
data := app.newTemplateData(r)
data.Snippets = snippets
2024-01-25 22:08:58 +00:00
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 ...
2024-01-26 06:01:12 +00:00
func (app *application) snippetView(w http.ResponseWriter, r *http.Request) {
params := httprouter.ParamsFromContext(r.Context())
id, err := strconv.Atoi(params.ByName("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 23:43:07 +00:00
data := app.newTemplateData(r)
data.Snippet = snippet
2024-01-25 21:41:06 +00:00
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
}
2024-01-26 06:01:12 +00:00
// (app *application) snippetCreate ...
func (app *application) snippetCreate(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Form for new snippet, plz?"))
}
2024-01-22 21:25:34 +00:00
2024-01-26 06:01:12 +00:00
// snippetCreatePost ...
func (app *application) snippetCreatePost(w http.ResponseWriter, r *http.Request) {
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
}
2024-01-26 06:01:12 +00:00
http.Redirect(w, r, fmt.Sprintf("/snippet/view/%d", id), http.StatusSeeOther)
2024-01-22 21:25:34 +00:00
}