t2/models/cod4cache.go

43 lines
852 B
Go

package models
import (
"fmt"
"time"
"github.com/patrickmn/go-cache"
)
type CachedProvider struct {
provider StatusProvider
cache *cache.Cache
}
func NewCachedProvider(provider StatusProvider) (*CachedProvider, error) {
c := cache.New(10*time.Second, 20*time.Second)
return &CachedProvider{
provider: provider,
cache: c,
}, nil
}
func (c *CachedProvider) GetServerStatus(host, port string, timeout time.Duration) (*CoD4ServerStatus, error) {
status, found := c.cache.Get(ID(host, port))
if found {
return status.(*CoD4ServerStatus), nil
} else {
status, err := c.provider.GetServerStatus(host, port, timeout)
if err != nil {
return nil, err
}
c.cache.Set(ID(host, port), status, cache.DefaultExpiration)
return status, nil
}
}
func ID(host, port string) string {
return fmt.Sprintf("%s:%s", host, port)
}