| 21 | } |
| 22 | |
| 23 | func (s *Singleton[T]) GetOpen(key string, open func() (T, error)) (T, error) { |
| 24 | s.lock.Lock() |
| 25 | defer s.lock.Unlock() |
| 26 | |
| 27 | existing, ok := s.resources[key] |
| 28 | if ok { |
| 29 | s.log.DebugMsg("resource reused", "key", key) |
| 30 | return existing, nil |
| 31 | } |
| 32 | |
| 33 | res, err := open() |
| 34 | if err != nil { |
| 35 | var empty T |
| 36 | return empty, err |
| 37 | } |
| 38 | |
| 39 | s.log.DebugMsg("new resource", "key", key) |
| 40 | s.resources[key] = res |
| 41 | |
| 42 | return res, nil |
| 43 | } |
| 44 | |
| 45 | func (s *Singleton[T]) CloseUnused(isUsed func(key string) bool) error { |
| 46 | s.lock.Lock() |