100-go-mistakes/11-testing/87-time-api/listing2/main.go
2021-12-27 15:56:17 +01:00

53 lines
748 B
Go

package listing1
import (
"sync"
"time"
)
type now func() time.Time
type Cache struct {
mu sync.RWMutex
events []Event
now now
}
func NewCache() *Cache {
return &Cache{
events: make([]Event, 0),
now: time.Now,
}
}
type Event struct {
Timestamp time.Time
Data string
}
func (c *Cache) TrimBefore(since time.Duration) {
c.mu.RLock()
defer c.mu.RUnlock()
t := time.Now().Add(-since)
for i := 0; i < len(c.events); i++ {
if c.events[i].Timestamp.After(t) {
c.events = c.events[i:]
return
}
}
}
func (c *Cache) Add(events []Event) {
c.mu.Lock()
defer c.mu.Unlock()
c.events = append(c.events, events...)
}
func (c *Cache) GetAll() []Event {
c.mu.RLock()
defer c.mu.RUnlock()
return c.events
}