diff --git a/cmd/web/handlers.go b/cmd/web/handlers.go index 42a2c3a..823be4c 100644 --- a/cmd/web/handlers.go +++ b/cmd/web/handlers.go @@ -1,10 +1,13 @@ package main import ( + "errors" "fmt" "html/template" "net/http" "strconv" + + "gitea.local.lab/Lbenedar/snippetbox/internal/models" ) func (app *application) home(w http.ResponseWriter, r *http.Request) { @@ -34,7 +37,17 @@ func (app *application) snippetView(w http.ResponseWriter, r *http.Request) { app.notFound(w) return } - fmt.Fprintf(w, "Display a specific snippet with ID %d...", id) + + snippet, err := app.snippets.Get(id) + if err != nil { + if errors.Is(err, models.ErrNoRecord) { + app.notFound(w) + } else { + app.serverError(w, err) + } + return + } + fmt.Fprintf(w, "%+v", snippet) } func (app *application) snippetCreate(w http.ResponseWriter, r *http.Request) { diff --git a/internal/models/errors.go b/internal/models/errors.go new file mode 100644 index 0000000..c7845a7 --- /dev/null +++ b/internal/models/errors.go @@ -0,0 +1,5 @@ +package models + +import "errors" + +var ErrNoRecord = errors.New("models: no matching record found") diff --git a/internal/models/snippets.go b/internal/models/snippets.go index ae56e6b..ad5389f 100644 --- a/internal/models/snippets.go +++ b/internal/models/snippets.go @@ -2,6 +2,7 @@ package models import ( "database/sql" + "errors" "time" ) @@ -33,7 +34,19 @@ func (m *SnippetModel) Insert(title string, content string, expires int) (int, e } func (m *SnippetModel) Get(id int) (*Snippet, error) { - return nil, nil + s := &Snippet{} + stmt := `SELECT id, title, content, created, expires FROM snippets + WHERE expires > UTC_TIMESTAMP() AND id = ?` + + err := m.DB.QueryRow(stmt, id).Scan(&s.ID, &s.Title, &s.Content, &s.Created, &s.Expires) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNoRecord + } else { + return nil, err + } + } + return s, nil } func (m *SnippetModel) Latest() ([]*Snippet, error) {