diff --git a/news/news.go b/news/news.go index d13dde0..4fa35b0 100644 --- a/news/news.go +++ b/news/news.go @@ -66,7 +66,7 @@ func addContainer(category_id int, flat, tree map[int]*NewsContainer) { } // Load and return in NewsContainer format all the unexported news items -func LoadPage(db *sql.DB, offset, amount int) (map[int]*NewsContainer, int, error) { +func LoadPage(db *sql.DB, offset, amount int) ([]News, int, error) { categories.LoadCategories(db) // required by addContainer rows, err := db.Query("SELECT url, title, category_id, timestamp, notes FROM news WHERE exported is null order by category_id ASC") @@ -76,7 +76,7 @@ func LoadPage(db *sql.DB, offset, amount int) (map[int]*NewsContainer, int, erro } defer rows.Close() - return convertSqlToNewsContainer(rows) + return convertSqlToNews(rows) } // Load and return in NewsContainer format all the unexported news items @@ -92,6 +92,43 @@ func Unexported(db *sql.DB) (map[int]*NewsContainer, int, error) { return convertSqlToNewsContainer(rows) } + +func convertSqlToNews(rows *sql.Rows) ([]News, int, error) { + news := []News{} + count := 0 + for rows.Next() { + newsItem := News{} + var url, title, notes sql.NullString + var date, category_id sql.NullInt64 + err := rows.Scan(&url, &title, &category_id, &newsItem.Date, ¬es) + if err != nil { + fmt.Println("Error reading news from DB: " + err.Error()) + return nil, 0, err + } + + newsItem.Url = nullStringToString(&url) + newsItem.Title = nullStringToString(&title) + newsItem.Notes = nullStringToString(¬es) + + if date.Valid { + newsItem.Date = time.Unix(date.Int64, 0) + } else { + newsItem.Date = time.Now() + } + + if category_id.Valid { + newsItem.Category_id = int(category_id.Int64) + } else { + continue // needs a category id + } + + + news = append(news, newsItem) + count++ + } + + return news, count, nil +} func convertSqlToNewsContainer(rows *sql.Rows) (map[int]*NewsContainer, int, error) { newsTree := map[int]*NewsContainer{} @@ -117,17 +154,16 @@ func convertSqlToNewsContainer(rows *sql.Rows) (map[int]*NewsContainer, int, err news.Date = time.Now() } - var cid int if category_id.Valid { - cid = int(category_id.Int64) + news.Category_id = int(category_id.Int64) } else { continue // needs a category id } - if _, ok := newsFlat[cid]; !ok { - addContainer(cid, newsFlat, newsTree) + if _, ok := newsFlat[news.Category_id]; !ok { + addContainer(news.Category_id, newsFlat, newsTree) } - container := newsFlat[cid] + container := newsFlat[news.Category_id] container.News = append(container.News, news) count++ } diff --git a/templates/pages/news.html b/templates/pages/news.html index 3985edd..15e48e4 100644 --- a/templates/pages/news.html +++ b/templates/pages/news.html @@ -9,6 +9,6 @@ {{define "row-news"}} - +