Skip to content

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

golang-gin-api

Verified

Build REST APIs with Go Gin. Use when creating Go web servers, adding Gin routes, writing handlers, or asking about middleware, binding, error handling, or project structure.

FileKindSize
SKILL.mdskill md10.0 KB
metadata.jsonconfig482 B
references/background-jobs-goroutine-and-pool.mdmarkdown3.5 KB
references/background-jobs-queue-and-shutdown.mdmarkdown3.5 KB
references/defensive-handler-patterns.mdmarkdown3.7 KB
references/error-handling-apperror.mdmarkdown4.1 KB
references/error-handling-recovery.mdmarkdown1.8 KB
references/error-handling-validation.mdmarkdown3.0 KB
references/file-uploads-cloud.mdmarkdown2.4 KB
references/file-uploads-local.mdmarkdown4.0 KB
references/middleware-core.mdmarkdown4.2 KB
references/middleware-logging-and-recovery.mdmarkdown3.3 KB
references/middleware-timeout-and-custom.mdmarkdown3.2 KB
references/rate-limiting-algorithms.mdmarkdown3.5 KB
references/rate-limiting-fallback.mdmarkdown2.3 KB
references/rate-limiting-headers.mdmarkdown1.8 KB
references/rate-limiting-peruser.mdmarkdown2.4 KB
references/rate-limiting-redis-sliding.mdmarkdown2.2 KB
references/rate-limiting-redis.mdmarkdown2.9 KB
references/rate-limiting-sliding-window.mdmarkdown2.2 KB
references/rate-limiting-tiered.mdmarkdown3.0 KB
references/routing-groups-and-versioning.mdmarkdown3.8 KB
references/routing-params-and-wildcards.mdmarkdown3.4 KB
references/routing-validators-and-limits.mdmarkdown2.4 KB
references/safe-context-extraction.mdmarkdown4.3 KB
references/server-handlers-and-errors.mdmarkdown3.6 KB
references/server-setup-and-routes.mdmarkdown3.9 KB
references/websocket-auth-and-keepalive.mdmarkdown3.5 KB
references/websocket-chat-handler.mdmarkdown1.5 KB
references/websocket-hub-and-client.mdmarkdown3.9 KB
references/websocket-setup-and-echo.mdmarkdown3.4 KB
references/websocket-shutdown-and-messages.mdmarkdown3.8 KB
references/websocket-testing.mdmarkdown3.8 KB

references/background-jobs-goroutine-and-pool.md

View on GitHub
# Background Jobs — Goroutine Pattern & Worker Pool

See also: `background-jobs-queue-and-shutdown.md`

## Common Use Cases

| Use Case | Recommended Pattern |
|----------|-------------------|
| Send email after signup | Simple goroutine |
| Generate PDF report | Worker pool |
| Process payment webhook | DB-backed queue |
| Sync data with external API | External queue (asynq) |

## Simple Goroutine Pattern

Use `c.Copy()` before passing `*gin.Context` to a goroutine. The original context is returned to the pool when the request ends — using it after that causes a data race.

```go
// internal/handler/user_handler.go
func (h *UserHandler) Create(c *gin.Context) {
    var req CreateUserRequest
    if err := c.ShouldBindJSON(&req); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
        return
    }

    user, err := h.userSvc.Create(c.Request.Context(), req)
    if err != nil {
        h.logger.Error("create user failed", "err", err)
        c.JSON(http.StatusInternalServerError, gin.H{"error": "could not create user"})
        return
    }

    // c.Copy() returns a shallow copy safe to use outside the request lifecycle
    cCopy := c.Copy()
    go func() {
        if err := h.emailSvc.SendWelcome(cCopy.Request.Context(), user); err != nil {
            h.logger.Error("welcome email failed", "userID", user.ID, "err", err)
        }
    }()

    c.JSON(http.StatusCreated, user)
}
```

**Warning:** fire-and-forget goroutines have no retry, no persistence, and are lost on process crash. Use only for non-critical side effects.

---

## Worker Pool Pattern

A buffered channel acts as a bounded job queue. Prevents unbounded goroutine spawning under load.

```go
// internal/worker/worker.go
type Job func(ctx context.Context)

type Worker struct {
    jobs   chan Job
    logger *slog.Logger
}

func NewWorker(bufferSize int, logger *slog.Logger) *Worker {
    return &Worker{
        jobs:   make(chan Job, bufferSize),
        logger: logger,
    }
}

// Submit enqueues a job. Returns error if the queue is full (non-blocking).
func (w *Worker) Submit(job Job) error {
    select {
    case w.jobs <- job:
        return nil
    default:
        return fmt.Errorf("worker queue full")
    }
}

// Start processes jobs until ctx is cancelled. Run in a goroutine.
func (w *Worker) Start(ctx context.Context) {
    for {
        select {
        case job := <-w.jobs:
            job(ctx)
        case <-ctx.Done():
            // Drain remaining jobs before exit
            for {
                select {
                case job := <-w.jobs:
                    job(ctx)
                default:
                    w.logger.Info("worker pool stopped")
                    return
                }
            }
        }
    }
}
```

Usage in a handler — submit without blocking the request:

```go
// internal/handler/report_handler.go
func (h *ReportHandler) Generate(c *gin.Context) {
    var req GenerateReportRequest
    if err := c.ShouldBindJSON(&req); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
        return
    }

    reportID := uuid.NewString()

    if err := h.worker.Submit(func(ctx context.Context) {
        if err := h.reportSvc.Generate(ctx, reportID, req); err != nil {
            h.logger.Error("report generation failed", "reportID", reportID, "err", err)
        }
    }); err != nil {
        c.JSON(http.StatusServiceUnavailable, gin.H{"error": "server busy, try again later"})
        return
    }

    c.JSON(http.StatusAccepted, gin.H{"report_id": reportID})
}
```
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 323kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 323kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 323kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 323kUpdated Claude CodeCodexVerifiedInstall