package data import ( "sync" "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 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), } } func (l *ArticleList) start() { l.wg.Done() 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 { var list []Article for _, article := range l.list { list = append(list, *article) } return list }(): } } } func NewArticleList() *ArticleList { list := minArticleList() list.list = []*Article{} list.wg.Add(1) go list.start() list.wg.Wait() 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) Get() []Article { return <-l.getCh }