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/server-handlers-and-errors.md

View on GitHub
# Server and Handlers — Thin Handlers, Sanitization & Error Handling

See also: `server-setup-and-routes.md`

## Domain Model

> **Architecture note:** Domain entities should not carry `json` or `binding` tags. Use separate request/response DTOs in the delivery layer.

```go
// internal/domain/user.go
package domain

import "time"

type User struct {
    ID           string    `json:"id"`
    Name         string    `json:"name"`
    Email        string    `json:"email"`
    PasswordHash string    `json:"-"` // never exposed via API
    Role         string    `json:"role"`
    CreatedAt    time.Time `json:"created_at"`
    UpdatedAt    time.Time `json:"updated_at"`
}

type CreateUserRequest struct {
    Name     string `json:"name"     binding:"required,min=2,max=100"`
    Email    string `json:"email"    binding:"required,email"`
    Password string `json:"password" binding:"required,min=8"`
    Role     string `json:"role"     binding:"omitempty,oneof=admin user"`
}
```

## Thin Handler Pattern

Handlers bind input, call a service, and format the response. No business logic.

```go
// internal/handler/user_handler.go
package handler

import (
    "log/slog"
    "net/http"

    "github.com/gin-gonic/gin"
    "myapp/internal/domain"
    "myapp/internal/service"
)

type UserHandler struct {
    svc    service.UserService
    logger *slog.Logger
}

func NewUserHandler(svc service.UserService, logger *slog.Logger) *UserHandler {
    return &UserHandler{svc: svc, logger: logger}
}

func (h *UserHandler) Create(c *gin.Context) {
    var req domain.CreateUserRequest
    if err := c.ShouldBindJSON(&req); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{
            "error":  "validation failed",
            "fields": validationErrors(err),
        })
        return
    }

    user, err := h.svc.Create(c.Request.Context(), req)
    if err != nil {
        handleServiceError(c, err, h.logger)
        return
    }

    c.JSON(http.StatusCreated, user)
}

func (h *UserHandler) GetByID(c *gin.Context) {
    type uriParams struct {
        ID string `uri:"id" binding:"required"`
    }
    var params uriParams
    if err := c.ShouldBindURI(&params); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request parameters"})
        return
    }

    user, err := h.svc.GetByID(c.Request.Context(), params.ID)
    if err != nil {
        handleServiceError(c, err, h.logger)
        return
    }

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

## Input Sanitization

Sanitize string fields **after** binding to neutralize injection payloads before they reach services or storage.

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

    req.Name  = strings.TrimSpace(req.Name)
    req.Name  = html.EscapeString(req.Name)
    req.Email = strings.TrimSpace(req.Email)
    req.Email = strings.ToLower(req.Email)

    user, err := h.svc.Create(c.Request.Context(), req)
    // ...
}
```

For file uploads, always strip directory components from client-supplied filenames:

```go
safeName := filepath.Base(file.Filename)
dst := filepath.Join("uploads", safeName)
```

## Goroutine Safety

**Always call `c.Copy()` before passing `*gin.Context` to a goroutine.** The original context is reused by the pool after the request ends.

```go
cCopy := c.Copy()
go func() {
    h.notifier.SendWelcome(cCopy.Request.Context(), user)
}()
```

See also: `background-jobs-goroutine-and-pool.md` for full goroutine + worker pool examples.
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: 322kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 322kUpdated 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: 322kUpdated 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: 322kUpdated Claude CodeCodexVerifiedInstall