Skip to content

henriqueatila/golang-gin-best-practices / skills/golang-gin-database

golang-gin-database

Verified

PostgreSQL integration for Go Gin with GORM/sqlx. Use when adding a database, writing queries, creating repositories, running migrations, or wiring DB layers in a Gin project.

references/redis-patterns-cache.md

View on GitHub
# Redis Patterns — Cache-Aside, Invalidation, and DI Wiring

Cache-aside pattern, cache invalidation on write, and dependency injection wiring.

## Cache-Aside Pattern

Check cache first; on miss, query DB, store result, return.

```go
// internal/service/user_service.go
func (s *userService) GetByID(ctx context.Context, id uint) (*domain.User, error) {
    cacheKey := fmt.Sprintf("user:%d", id)

    // 1. Check cache
    cached, err := s.cache.Get(ctx, cacheKey)
    if err == nil {
        var user domain.User
        if jsonErr := json.Unmarshal([]byte(cached), &user); jsonErr == nil {
            return &user, nil
        }
    }

    // 2. Cache miss — query DB
    user, err := s.repo.GetByID(ctx, id)
    if err != nil {
        return nil, err
    }

    // 3. Populate cache (fire-and-forget acceptable for non-critical data)
    _ = s.cache.Set(ctx, cacheKey, user, 5*time.Minute)

    return user, nil
}
```

## Cache Invalidation — Delete on Write

```go
func (s *userService) Update(ctx context.Context, id uint, input domain.UpdateUserInput) (*domain.User, error) {
    user, err := s.repo.Update(ctx, id, input)
    if err != nil {
        return nil, err
    }
    // Invalidate stale entry immediately after write
    _ = s.cache.Delete(ctx, fmt.Sprintf("user:%d", id))
    return user, nil
}
```

## Dependency Injection in main.go

```go
// main.go (excerpt)
rdb, err := infrastructure.NewRedisClient(ctx, logger)
if err != nil {
    logger.Error("redis init failed", "err", err)
    os.Exit(1)
}
defer rdb.Close()

cacheRepo := repository.NewRedisCacheRepository(rdb)
blacklist  := repository.NewTokenBlacklist(rdb)
userSvc    := service.NewUserService(userRepo, cacheRepo, logger)

r := gin.New()
r.Use(middleware.SlidingWindowRateLimiter(rdb, 100, time.Minute))
```

For JWT blacklist, sliding-window rate limiter, health check, and docker-compose config: see [redis-patterns-advanced.md](redis-patterns-advanced.md).
deprecation-and-migrationaddyosmani/agent-skillsManages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when migrating a database schema in production, such as renaming or dropping a column without downtime (expand/contract). Use when deciding whether to maintain or sunset existing code.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
performance-optimizationaddyosmani/agent-skillsOptimizes application performance across frontend, backend, queries, and databases. Use when performance requirements exist, when you suspect performance regressions, when Core Web Vitals or load times need improvement, when N+1 query patterns need fixing, or when profiling reveals bottlenecks.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
agent-cost-reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json.Stars: 118kUpdated Claude CodeCodexVerifiedInstall
agent-cost-reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json.Stars: 118kUpdated Claude CodeCodexVerifiedInstall