85 lines
1.8 KiB
Go
85 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/julienschmidt/httprouter"
|
|
"snippetbox.chaosfem.tw/internal/models"
|
|
)
|
|
|
|
// home ...
|
|
func (app *application) home(w http.ResponseWriter, r *http.Request) {
|
|
snippets, err := app.snippets.Latest()
|
|
if err != nil {
|
|
app.serverError(w, r, err)
|
|
return
|
|
}
|
|
|
|
data := app.newTemplateData(r)
|
|
data.Snippets = snippets
|
|
|
|
app.render(w, r, http.StatusOK, "home.tmpl", data)
|
|
}
|
|
|
|
// snippetView ...
|
|
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
|
|
}
|
|
|
|
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 := app.newTemplateData(r)
|
|
data.Snippet = snippet
|
|
|
|
app.render(w, r, http.StatusOK, "view.tmpl", data)
|
|
}
|
|
|
|
// (app *application) snippetCreate ...
|
|
func (app *application) snippetCreate(w http.ResponseWriter, r *http.Request) {
|
|
data := app.newTemplateData(r)
|
|
|
|
app.render(w, r, http.StatusOK, "create.tmpl", data)
|
|
}
|
|
|
|
// snippetCreatePost ...
|
|
func (app *application) snippetCreatePost(w http.ResponseWriter, r *http.Request) {
|
|
err := r.ParseForm()
|
|
if err != nil {
|
|
app.clientError(w, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
title := r.PostForm.Get("title")
|
|
content := r.PostForm.Get("content")
|
|
|
|
expires, err := strconv.Atoi(r.PostForm.Get("expires"))
|
|
if err != nil {
|
|
app.clientError(w, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
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/%d", id), http.StatusSeeOther)
|
|
}
|