refactor: replace standard log with zap logger and optimize code patterns

- Migrate all log.Printf/log.Println calls to structured zap logging
- Use cmp.Or for cleaner default value handling
- Replace manual loops with slices.ContainsFunc/IndexFunc
- Add batch query methods (IsLikedBatch, IsFavoritedBatch) to solve N+1 problem
- Update JSON tags from omitempty to omitzero for numeric fields
- Use errgroup-style wg.Go for worker goroutines
- Remove duplicate casbin/v2 dependency (keeping v3)
- Add plans/ to gitignore
This commit is contained in:
lafay
2026-03-17 00:47:17 +08:00
parent b028f7e1d3
commit 5d6c982c9c
38 changed files with 2256 additions and 290 deletions

View File

@@ -1,7 +1,6 @@
package wire
import (
"log"
"time"
"carrot_bbs/internal/cache"
@@ -62,7 +61,9 @@ func ProvideDB(cfg *config.Config) (*gorm.DB, error) {
func ProvideRedisClient(cfg *config.Config) *redis.Client {
client, err := redis.New(&cfg.Redis)
if err != nil {
log.Printf("[WARNING] Failed to connect to Redis: %v, falling back to memory cache", err)
zap.L().Warn("Failed to connect to Redis, falling back to memory cache",
zap.Error(err),
)
return nil
}
return client
@@ -85,12 +86,12 @@ func ProvideCache(cfg *config.Config, redisClient *redis.Client) cache.Cache {
// 直接创建 RedisCache 实例,不依赖全局变量
if redisClient == nil {
log.Println("[Wire] Warning: Redis client is nil, cache will not be available")
zap.L().Warn("Redis client is nil, cache will not be available")
return nil
}
cacheInstance := cache.NewRedisCache(redisClient)
log.Println("[Wire] Initialized Redis cache via dependency injection")
zap.L().Info("Initialized Redis cache via dependency injection")
return cacheInstance
}
@@ -128,7 +129,9 @@ func ProvideTransactionManager(db *gorm.DB) repository.TransactionManager {
func ProvideLogger() *zap.Logger {
logger, err := zap.NewProduction()
if err != nil {
log.Fatalf("Failed to create logger: %v", err)
panic("Failed to create logger: " + err.Error())
}
// 设置为全局 logger以便在其他地方使用 zap.L()
zap.ReplaceGlobals(logger)
return logger
}