add limit to index page, for performance improvements
This commit is contained in:
@@ -8,23 +8,24 @@ import (
|
|||||||
|
|
||||||
// List the latest articles using the base template.
|
// List the latest articles using the base template.
|
||||||
func (app *App) Index(w http.ResponseWriter, req *http.Request) {
|
func (app *App) Index(w http.ResponseWriter, req *http.Request) {
|
||||||
// get articles
|
// get articles
|
||||||
articles, err := app.articles.All()
|
articles, err := app.articles.All(10)
|
||||||
if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError); return; }
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// truncate
|
// convert to viewmodel
|
||||||
if len(articles) > 10 {
|
articleVMs := make([]*model.ArticleViewModel, 0, len(articles))
|
||||||
articles = articles[:10]
|
for _, a := range articles {
|
||||||
}
|
articleVMs = append(articleVMs, a.ViewModel())
|
||||||
|
}
|
||||||
|
|
||||||
// convert to viewmodel
|
// render template
|
||||||
articleVMs := make([]*model.ArticleViewModel, 0, len(articles))
|
t := template.Must(template.ParseFiles("assets/templates/article.html", "assets/templates/layout.html"))
|
||||||
for _, a := range articles {
|
err = t.ExecuteTemplate(w, "base", articleVMs)
|
||||||
articleVMs = append(articleVMs, a.ViewModel())
|
if err != nil {
|
||||||
}
|
http.Error(w, "Failed to render template", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
// render template
|
}
|
||||||
t := template.Must(template.ParseFiles("assets/templates/article.html", "assets/templates/layout.html"))
|
|
||||||
err = t.ExecuteTemplate(w, "base", articleVMs)
|
|
||||||
if err != nil { http.Error(w, "Failed to render template", http.StatusInternalServerError); return; }
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,13 +11,14 @@ type ArticleModel struct {
|
|||||||
|
|
||||||
// Gets all the article objects from the database. This may throw an error if
|
// Gets all the article objects from the database. This may throw an error if
|
||||||
// the connection to the database fails.
|
// the connection to the database fails.
|
||||||
func (m *ArticleModel) All() ([]model.Article, error) {
|
func (m *ArticleModel) All(limit int) ([]model.Article, error) {
|
||||||
stmt := `
|
stmt := `
|
||||||
SELECT id, title, sourceUrl, author, content, publishDate, fetchDate
|
SELECT id, title, sourceUrl, author, content, publishDate, fetchDate
|
||||||
FROM articles
|
FROM articles
|
||||||
ORDER BY publishDate DESC
|
ORDER BY publishDate DESC
|
||||||
|
LIMIT $1
|
||||||
`
|
`
|
||||||
rows, err := m.DB.Query(stmt)
|
rows, err := m.DB.Query(stmt, limit)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user