80 lines
1.7 KiB
Go
80 lines
1.7 KiB
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"gitea.local.lab/Lbenedar/snippetbox/internal/models"
|
|
)
|
|
|
|
func (app *application) render(w http.ResponseWriter, status int, page string, data *templateData) {
|
|
ts, ok := app.templateCache[page]
|
|
if !ok {
|
|
err := fmt.Errorf("the template %s does not exist", page)
|
|
app.serverError(w, err)
|
|
return
|
|
}
|
|
w.WriteHeader(status)
|
|
err := ts.ExecuteTemplate(w, "base", data)
|
|
if err != nil {
|
|
app.serverError(w, err)
|
|
}
|
|
}
|
|
|
|
func (app *application) home(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/" {
|
|
app.notFound(w)
|
|
return
|
|
}
|
|
|
|
snippets, err := app.snippets.Latest()
|
|
if err != nil {
|
|
app.serverError(w, err)
|
|
return
|
|
}
|
|
app.render(w, http.StatusOK, "home.tmpl", &templateData{
|
|
Snippets: snippets,
|
|
})
|
|
}
|
|
|
|
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 {
|
|
if errors.Is(err, models.ErrNoRecord) {
|
|
app.notFound(w)
|
|
} else {
|
|
app.serverError(w, err)
|
|
}
|
|
return
|
|
}
|
|
app.render(w, http.StatusOK, "view.tmpl", &templateData{
|
|
Snippet: snippet,
|
|
})
|
|
}
|
|
|
|
func (app *application) snippetCreate(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
w.Header().Set("Allow", http.MethodPost)
|
|
app.clientError(w, http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
title := "0 snail"
|
|
content := "0 snail\nClimb Mount Fuji,\nBut slowly, slowly!\n\n-Kobayshi Issa"
|
|
expires := 7
|
|
|
|
id, err := app.snippets.Insert(title, content, expires)
|
|
if err != nil {
|
|
app.serverError(w, err)
|
|
return
|
|
}
|
|
http.Redirect(w, r, fmt.Sprintf("/snippet/view?id=%d", id), http.StatusSeeOther)
|
|
}
|