77 lines
1.3 KiB
Go
77 lines
1.3 KiB
Go
package data
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type Article struct {
|
|
Title string
|
|
Created time.Time
|
|
Desc string
|
|
Content string
|
|
Tags []string
|
|
UUID uuid.UUID
|
|
}
|
|
|
|
type ArticleList struct {
|
|
addCh chan *Article
|
|
delCh chan uuid.UUID
|
|
retCh chan *Article
|
|
listCh chan []Article
|
|
list []*Article
|
|
}
|
|
|
|
func (l *ArticleList) start() {
|
|
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.listCh <- func() []Article {
|
|
var list []Article
|
|
for _, article := range l.list {
|
|
list = append(list, *article)
|
|
}
|
|
return list
|
|
}():
|
|
}
|
|
}
|
|
}
|
|
|
|
func NewArticleList() *ArticleList {
|
|
list := &ArticleList{
|
|
addCh: make(chan *Article),
|
|
delCh: make(chan uuid.UUID),
|
|
retCh: make(chan *Article),
|
|
listCh: make(chan []Article),
|
|
list: []*Article{},
|
|
}
|
|
go list.start()
|
|
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
|
|
}
|
|
return article, true
|
|
}
|
|
|
|
func (l *ArticleList) List() []Article {
|
|
return <-l.listCh
|
|
}
|