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:
@@ -1,10 +1,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -73,17 +75,17 @@ func main() {
|
||||
defer sqlDB.Close()
|
||||
|
||||
if err := sqlDB.Ping(); err != nil {
|
||||
log.Fatalf("Failed to ping database: %v", err)
|
||||
zap.L().Fatal("Failed to ping database", zap.Error(err))
|
||||
}
|
||||
|
||||
log.Println("Connected to database")
|
||||
zap.L().Info("Connected to database")
|
||||
|
||||
// 运行迁移
|
||||
if err := runMigration(db); err != nil {
|
||||
log.Fatalf("Migration failed: %v", err)
|
||||
zap.L().Fatal("Migration failed", zap.Error(err))
|
||||
}
|
||||
|
||||
log.Println("Migration completed successfully")
|
||||
zap.L().Info("Migration completed successfully")
|
||||
}
|
||||
|
||||
func runMigration(db *gorm.DB) error {
|
||||
@@ -105,26 +107,31 @@ func runMigration(db *gorm.DB) error {
|
||||
}
|
||||
|
||||
if hasPreviewURL && hasPreviewURLLarge {
|
||||
log.Println("Columns already exist, skipping migration")
|
||||
zap.L().Info("Columns already exist, skipping migration")
|
||||
return nil
|
||||
}
|
||||
|
||||
// 添加字段
|
||||
var errs []error
|
||||
if !hasPreviewURL {
|
||||
log.Println("Adding preview_url column...")
|
||||
zap.L().Info("Adding preview_url column...")
|
||||
if err := db.Exec("ALTER TABLE post_images ADD COLUMN preview_url TEXT").Error; err != nil {
|
||||
return fmt.Errorf("failed to add preview_url column: %w", err)
|
||||
errs = append(errs, fmt.Errorf("failed to add preview_url column: %w", err))
|
||||
}
|
||||
}
|
||||
|
||||
if !hasPreviewURLLarge {
|
||||
log.Println("Adding preview_url_large column...")
|
||||
zap.L().Info("Adding preview_url_large column...")
|
||||
if err := db.Exec("ALTER TABLE post_images ADD COLUMN preview_url_large TEXT").Error; err != nil {
|
||||
return fmt.Errorf("failed to add preview_url_large column: %w", err)
|
||||
errs = append(errs, fmt.Errorf("failed to add preview_url_large column: %w", err))
|
||||
}
|
||||
}
|
||||
|
||||
log.Println("Migration completed successfully")
|
||||
if len(errs) > 0 {
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
zap.L().Info("Migration completed successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user