answer/pkg/cache/memory.go
Steve Dudenhoeffer 6c30fdf4d8 Add DuckDuckGo support and refactor caching system
Introduced DuckDuckGo as a new search provider alongside Google. Implemented a flexible caching system with in-memory, file-based, and no-op cache options to improve modularity. Updated dependencies and revised the project structure for improved maintainability.
2025-02-21 18:40:25 -05:00

79 lines
1.2 KiB
Go

package cache
import (
"encoding/json"
"io"
)
type memoryCache struct {
data map[string][]byte
}
var _ Cache = &memoryCache{}
func NewMemoryCache() (Cache, error) {
return &memoryCache{
data: make(map[string][]byte),
}, nil
}
func (m *memoryCache) Get(key string, writer io.Writer) error {
data, ok := m.data[key]
if ok {
_, err := writer.Write(data)
return err
}
return ErrNotFound
}
func (m *memoryCache) GetString(key string) (string, error) {
data, ok := m.data[key]
if ok {
return string(data), nil
}
return "", ErrNotFound
}
func (m *memoryCache) GetJSON(key string, value interface{}) error {
data, ok := m.data[key]
if ok {
return json.Unmarshal(data, value)
}
return ErrNotFound
}
func (m *memoryCache) Set(key string, value io.Reader) error {
data, err := io.ReadAll(value)
if err != nil {
return err
}
m.data[key] = data
return nil
}
func (m *memoryCache) SetJSON(key string, value interface{}) error {
data, err := json.Marshal(value)
if err != nil {
return err
}
m.data[key] = data
return nil
}
func (m *memoryCache) SetString(key string, value string) error {
m.data[key] = []byte(value)
return nil
}
func (m *memoryCache) Delete(key string) error {
delete(m.data, key)
return nil
}