GoDoxy/internal/utils/pool/pool.go
Yuzerion 04f806239d
refactor: organize code (#90)
* fix: improved sync.Pool handling

* refactor: ping if-flow and remove timeout

* refactor: enhance favicon fetching with context support and improve cache management

- Added context support to favicon fetching functions to handle timeouts and cancellations.
- Improved cache entry structure to include content type and utilize atomic values for last access time.
- Implemented maximum cache size and entry limits to optimize memory usage.
- Updated error handling for HTTP requests and refined the logic for managing redirects.

* fix: log formatting

* feat(pool): add checkExists method to debug build to detect unexpected behavior

* chore: cont. 0866feb

* refactor: unify route handling by consolidating route query methods with Pool

- Replaced direct calls to routequery with a new routes package for better organization and maintainability.
- Updated various components to utilize the new routes methods for fetching health information, homepage configurations, and route aliases.
- Enhanced the overall structure of the routing logic to improve clarity and reduce redundancy.

* chore: uncomment icon list cache code

* refactor: update task management code

- Rename needFinish to waitFinish
- Fixed some tasks not being waited they should be
- Adjusted mutex usage in the directory watcher to utilize read-write locks for improved concurrency management.

* refactor: enhance idlewatcher logging and exit handling

* fix(server): ensure HTTP handler is set only if initialized

* refactor(accesslog): replace JSON log entry struct with zerolog for improved logging efficiency, updated test

* refactor: remove test run code

---------

Co-authored-by: yusing <yusing@6uo.me>
2025-04-17 15:30:05 +08:00

65 lines
1.1 KiB
Go

package pool
import (
"sort"
"github.com/puzpuzpuz/xsync/v3"
"github.com/yusing/go-proxy/internal/logging"
)
type (
Pool[T Object] struct {
m *xsync.MapOf[string, T]
name string
}
Object interface {
Key() string
Name() string
}
)
func New[T Object](name string) Pool[T] {
return Pool[T]{xsync.NewMapOf[string, T](), name}
}
func (p Pool[T]) Name() string {
return p.name
}
func (p Pool[T]) Add(obj T) {
p.checkExists(obj.Key())
p.m.Store(obj.Key(), obj)
logging.Info().Msgf("%s: added %s", p.name, obj.Name())
}
func (p Pool[T]) Del(obj T) {
p.m.Delete(obj.Key())
logging.Info().Msgf("%s: removed %s", p.name, obj.Name())
}
func (p Pool[T]) Get(key string) (T, bool) {
return p.m.Load(key)
}
func (p Pool[T]) Size() int {
return p.m.Size()
}
func (p Pool[T]) Clear() {
p.m.Clear()
}
func (p Pool[T]) Iter(fn func(k string, v T) bool) {
p.m.Range(fn)
}
func (p Pool[T]) Slice() []T {
slice := make([]T, 0, p.m.Size())
for _, v := range p.m.Range {
slice = append(slice, v)
}
sort.Slice(slice, func(i, j int) bool {
return slice[i].Name() < slice[j].Name()
})
return slice
}