Added ability to publish articles

This commit is contained in:
2024-03-01 11:30:31 +01:00
parent cba3c663c9
commit f59321b9c6
10 changed files with 127 additions and 84 deletions

View File

@ -1,58 +1,41 @@
package data
import "time"
import (
"sync"
"time"
"github.com/google/uuid"
)
type Article struct {
Title string
Created time.Time
Desc string
Content string
UUID uuid.UUID
}
type ArticleList struct {
addChan chan Article
releaseChan chan int
returnChan chan Article
List []Article
}
func (l *ArticleList) start() {
for {
select {
case article := <-l.addChan:
l.List = append(l.List, article)
case i := <-l.releaseChan:
l.returnChan <- l.List[i]
l.List = append(l.List[:i], l.List[i+1:]...)
}
}
}
func NewArticleList() *ArticleList {
list := &ArticleList{
List: []Article{},
addChan: make(chan Article),
releaseChan: make(chan int),
returnChan: make(chan Article),
}
list.start()
return list
}
func (l *ArticleList) Close() {
close(l.addChan)
close(l.releaseChan)
close(l.returnChan)
List []Article
sync.Mutex
}
func (l *ArticleList) Add(a Article) {
l.addChan <- a
l.Lock()
l.List = append(l.List, a)
l.Unlock()
}
func (l *ArticleList) Release(i int) (Article, bool) {
if i < 0 || i > len(l.List) {
return Article{}, false
func (l *ArticleList) Release(uuid uuid.UUID) (Article, bool) {
l.Lock()
for i, article := range l.List {
if article.UUID == uuid {
foo := l.List[i]
l.List = append(l.List[:i], l.List[i+1:]...)
l.Unlock()
return foo, true
}
}
l.releaseChan <- i
return <-l.returnChan, true
l.Unlock()
return Article{}, false
}

View File

@ -4,36 +4,24 @@ import (
"encoding/gob"
"fmt"
"os"
"sync"
"github.com/gorilla/feeds"
)
type Feed struct {
feeds.Feed
addChan chan *feeds.Item
}
func (f *Feed) start() {
for item := range f.addChan {
f.Items = append(f.Items, item)
}
sync.Mutex
}
func NewFeed(title, link, desc string) *Feed {
feed := &Feed{
return &Feed{
Feed: feeds.Feed{
Title: title,
Link: &feeds.Link{Href: link},
Description: desc,
},
addChan: make(chan *feeds.Item),
}
feed.start()
return feed
}
func (f *Feed) Close() {
close(f.addChan)
}
func OpenFeed(filename string) (*Feed, error) {
@ -49,8 +37,6 @@ func OpenFeed(filename string) (*Feed, error) {
if err != nil {
return nil, fmt.Errorf("error decoding file %v: %v", filename, err)
}
feed.addChan = make(chan *feeds.Item)
feed.start()
return feed, nil
}
@ -63,7 +49,9 @@ func (f *Feed) Save(filename string) error {
defer file.Close()
encoder := gob.NewEncoder(file)
f.Lock()
err = encoder.Encode(f.Feed)
f.Unlock()
if err != nil {
return fmt.Errorf("error encoding file %v: %v", filename, err)
}
@ -72,5 +60,7 @@ func (f *Feed) Save(filename string) error {
}
func (f *Feed) Add(i *feeds.Item) {
f.addChan <- i
f.Lock()
f.Items = append(f.Items, i)
f.Unlock()
}