/
uzer_007
/
Rixea
Обзор
Документация
Войти
/
uzer_007
/
Rixea
Код
Запросы
0
Задачи
Вики
Пакеты
5
Релизы
2
CI/CD
Аналитика
Безопасность
master
modules/cache/string_cache.go
118 строк
3 KB
uzer_007
feat: первая версия Rixea
02 авг 2026, 22:16
02 авг 2026, 22:16
d4f7504
Код
Авторство
О чём код?
// Copyright 2026 Uzer_007. All rights reserved. // SPDX-License-Identifier: MIT package cache import ( "errors" "strings" "gitverse.ru/uzer_007/Rixea/modules/json" "gitverse.ru/uzer_007/Rixea/modules/setting" "gitverse.ru/uzer_007/Rixea/modules/util" ) type GetJSONError struct { err error cachedError string // Golang error can't be stored in cache, only the string message could be stored } func (e *GetJSONError) ToError() error { if e.err != nil { return e.err } return errors.New("cached error: " + e.cachedError) } type StringCache interface { Ping() error Get(key string) (string, bool) Put(key, value string, ttl int64) error Delete(key string) error IsExist(key string) bool PutJSON(key string, v any, ttl int64) error GetJSON(key string, ptr any) (exist bool, err *GetJSONError) ChiCache() Cache } type stringCache struct { chiCache Cache } func NewStringCache(cacheConfig setting.Cache) (StringCache, error) { adapter := util.IfZero(cacheConfig.Adapter, "memory") interval := util.IfZero(cacheConfig.Interval, 60) cc, err := NewCacher(Options{ Adapter: adapter, AdapterConfig: cacheConfig.Conn, Interval: interval, }) if err != nil { return nil, err } return &stringCache{chiCache: cc}, nil } func (sc *stringCache) Ping() error { return sc.chiCache.Ping() } func (sc *stringCache) Get(key string) (string, bool) { v := sc.chiCache.Get(key) if v == nil { return "", false } s, ok := v.(string) return s, ok } func (sc *stringCache) Put(key, value string, ttl int64) error { return sc.chiCache.Put(key, value, ttl) } func (sc *stringCache) Delete(key string) error { return sc.chiCache.Delete(key) } func (sc *stringCache) IsExist(key string) bool { return sc.chiCache.IsExist(key) } const cachedErrorPrefix = "<CACHED-ERROR>:" func (sc *stringCache) PutJSON(key string, v any, ttl int64) error { var s string switch v := v.(type) { case error: s = cachedErrorPrefix + v.Error() default: b, err := json.Marshal(v) if err != nil { return err } s = util.UnsafeBytesToString(b) } return sc.chiCache.Put(key, s, ttl) } func (sc *stringCache) GetJSON(key string, ptr any) (exist bool, getErr *GetJSONError) { s, ok := sc.Get(key) if !ok || s == "" { return false, nil } s, isCachedError := strings.CutPrefix(s, cachedErrorPrefix) if isCachedError { return true, &GetJSONError{cachedError: s} } if err := json.Unmarshal(util.UnsafeStringToBytes(s), ptr); err != nil { return false, &GetJSONError{err: err} } return true, nil } func (sc *stringCache) ChiCache() Cache { return sc.chiCache }