54 lines
956 B
Go
54 lines
956 B
Go
package helper
|
|
|
|
import (
|
|
"os"
|
|
"time"
|
|
)
|
|
|
|
// Returns env with default fallback value.
|
|
//
|
|
// Params:
|
|
//
|
|
// key - enviroment var name
|
|
// fallback - default value
|
|
func GetEnv(key, fallback string) string {
|
|
if value, ok := os.LookupEnv(key); ok {
|
|
return value
|
|
}
|
|
return fallback
|
|
}
|
|
|
|
type CacheItem struct {
|
|
value any
|
|
expiration time.Time
|
|
}
|
|
|
|
type Cache struct {
|
|
data map[string]CacheItem
|
|
ttl time.Duration
|
|
fetch func(key string) (any, error)
|
|
}
|
|
|
|
func NewCache(ttl time.Duration, fetchFunc func(key string) (any, error)) *Cache {
|
|
return &Cache{
|
|
data: make(map[string]CacheItem),
|
|
ttl: ttl,
|
|
fetch: fetchFunc,
|
|
}
|
|
}
|
|
|
|
func (c *Cache) Get(key string) (any, error) {
|
|
if item, found := c.data[key]; found {
|
|
if time.Now().Before(item.expiration) {
|
|
return item.value, nil
|
|
}
|
|
}
|
|
|
|
value, err := c.fetch(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
c.data[key] = CacheItem{value: value, expiration: time.Now().Add(c.ttl)}
|
|
return value, nil
|
|
}
|