cpolis/cmd/data/articles.go

90 lines
1.5 KiB
Go
Raw Normal View History

package data
2024-03-01 11:30:31 +01:00
import (
"sync"
2024-03-01 11:30:31 +01:00
"time"
"github.com/google/uuid"
)
type Article struct {
2024-03-03 09:16:49 +01:00
Title string
Author string
Created time.Time
Desc string
Content string
Tags []string
UUID uuid.UUID
AuthorID int64
}
type ArticleList struct {
addCh chan *Article
delCh chan uuid.UUID
retCh chan *Article
getCh chan []Article
list []*Article
wg sync.WaitGroup
}
func minArticleList() *ArticleList {
return &ArticleList{
addCh: make(chan *Article),
delCh: make(chan uuid.UUID),
retCh: make(chan *Article),
getCh: make(chan []Article),
}
}
2024-03-01 21:01:38 +01:00
func (l *ArticleList) start() {
l.wg.Done()
2024-03-01 21:01:38 +01:00
for {
select {
case article := <-l.addCh:
l.list = append(l.list, article)
case uuid := <-l.delCh:
for i, article := range l.list {
if article.UUID == uuid {
l.list = append(l.list[:i], l.list[i+1:]...)
l.retCh <- article
}
}
case l.getCh <- func() []Article {
2024-03-01 21:01:38 +01:00
var list []Article
for _, article := range l.list {
list = append(list, *article)
}
return list
}():
}
}
}
2024-03-01 21:01:38 +01:00
func NewArticleList() *ArticleList {
list := minArticleList()
list.list = []*Article{}
list.wg.Add(1)
2024-03-01 21:01:38 +01:00
go list.start()
list.wg.Wait()
2024-03-01 21:01:38 +01:00
return list
}
func (l *ArticleList) Add(a *Article) {
l.addCh <- a
}
func (l *ArticleList) Release(uuid uuid.UUID) (*Article, bool) {
l.delCh <- uuid
article := <-l.retCh
if article == nil {
return nil, false
}
2024-03-01 21:01:38 +01:00
return article, true
}
func (l *ArticleList) Get() []Article {
return <-l.getCh
}