This commit is contained in:
lbenedar
2026-03-04 17:01:30 +03:00
parent e5288f0d33
commit c5833c6ddf
3 changed files with 33 additions and 2 deletions

View File

@@ -1,10 +1,13 @@
package main package main
import ( import (
"errors"
"fmt" "fmt"
"html/template" "html/template"
"net/http" "net/http"
"strconv" "strconv"
"gitea.local.lab/Lbenedar/snippetbox/internal/models"
) )
func (app *application) home(w http.ResponseWriter, r *http.Request) { 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) app.notFound(w)
return 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) { func (app *application) snippetCreate(w http.ResponseWriter, r *http.Request) {

View File

@@ -0,0 +1,5 @@
package models
import "errors"
var ErrNoRecord = errors.New("models: no matching record found")

View File

@@ -2,6 +2,7 @@ package models
import ( import (
"database/sql" "database/sql"
"errors"
"time" "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) { 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) { func (m *SnippetModel) Latest() ([]*Snippet, error) {