Skip to content

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

golang-gin-architect

Verified

Software architect for Go Gin APIs. Use when making architecture decisions, evaluating complexity, designing systems, choosing patterns, or coordinating across gin skills.

FileKindSize
SKILL.mdskill md10.7 KB
metadata.jsonconfig466 B
references/adr-format-and-templates.mdmarkdown4.1 KB
references/adr-service-extraction-and-example.mdmarkdown4.0 KB
references/api-design-error-contract-docs.mdmarkdown1.8 KB
references/api-design-filtering-bulk-evolution.mdmarkdown3.8 KB
references/api-design-versioning-pagination.mdmarkdown4.3 KB
references/clean-architecture-feature-module.mdmarkdown4.5 KB
references/clean-architecture-layers-di.mdmarkdown5.2 KB
references/complexity-assessment-budget.mdmarkdown5.6 KB
references/complexity-assessment-gates.mdmarkdown4.2 KB
references/complexity-assessment-patterns.mdmarkdown5.0 KB
references/cross-cutting-health-checks.mdmarkdown1.7 KB
references/cross-cutting-observability.mdmarkdown3.9 KB
references/cross-cutting-security-config.mdmarkdown4.4 KB
references/data-ownership-boundaries.mdmarkdown4.5 KB
references/data-ownership-sync-migration.mdmarkdown4.3 KB
references/data-patterns-cqrs.mdmarkdown3.8 KB
references/data-patterns-event-sourcing-aggregate.mdmarkdown2.2 KB
references/data-patterns-event-store.mdmarkdown3.7 KB
references/data-patterns-outbox.mdmarkdown3.7 KB
references/data-patterns-read-replicas.mdmarkdown2.6 KB
references/data-patterns-saga.mdmarkdown3.6 KB
references/error-flow-domain-layers.mdmarkdown5.3 KB
references/error-flow-handler-chain.mdmarkdown4.7 KB
references/golden-main-medium-project.mdmarkdown3.0 KB
references/golden-main-medium-startup.mdmarkdown2.8 KB
references/golden-main-small-project.mdmarkdown4.0 KB
references/grpc-interop-gateway-docker.mdmarkdown2.1 KB
references/grpc-interop-server-client.mdmarkdown2.7 KB
references/grpc-interop-setup.mdmarkdown3.6 KB
references/messaging-consumer-docker.mdmarkdown1.6 KB
references/messaging-consumer-workqueues.mdmarkdown3.6 KB
references/messaging-dlq-idempotency.mdmarkdown3.1 KB
references/messaging-dlq-setup.mdmarkdown2.4 KB
references/messaging-pubsub-exchanges.mdmarkdown3.6 KB
references/messaging-rabbitmq-connection.mdmarkdown3.2 KB
references/messaging-rabbitmq-producer.mdmarkdown2.4 KB
references/object-storage-download-presign.mdmarkdown3.5 KB
references/object-storage-multipart-minio.mdmarkdown2.2 KB
references/object-storage-setup-upload.mdmarkdown4.2 KB
references/redis-cache-warming-pubsub.mdmarkdown3.2 KB
references/redis-caching-patterns.mdmarkdown4.3 KB
references/redis-session-distributed-lock.mdmarkdown3.9 KB
references/resilience-circuit-breaker-bulkhead.mdmarkdown4.3 KB
references/resilience-retry-rate-limiting.mdmarkdown4.0 KB
references/skill-orchestration-overview.mdmarkdown3.2 KB
references/skill-orchestration-workflows.mdmarkdown5.4 KB
references/system-design-bounded-contexts.mdmarkdown4.1 KB
references/system-design-c4-model.mdmarkdown4.6 KB
references/system-design-dependency-graphs.mdmarkdown2.6 KB
references/system-design-domain-modeling.mdmarkdown3.5 KB
references/system-design-project-structure.mdmarkdown4.2 KB
references/tech-debt-identification-prioritization.mdmarkdown5.1 KB
references/tech-debt-refactoring-communication.mdmarkdown4.0 KB

references/api-design-versioning-pagination.md

View on GitHub
# API Design — Versioning and Pagination

Deep-dive reference for API versioning and pagination patterns in Go Gin APIs.

---

## Versioning Strategies

### URL Path Versioning (Recommended)

Simplest, most visible, easiest to test and debug.

```go
func registerRoutes(r *gin.Engine, v1 V1Handlers, v2 V2Handlers) {
    apiV1 := r.Group("/api/v1")
    {
        apiV1.GET("/users", v1.ListUsers)
        apiV1.GET("/users/:id", v1.GetUser)
        apiV1.POST("/users", v1.CreateUser)
    }

    apiV2 := r.Group("/api/v2")
    {
        apiV2.GET("/users", v2.ListUsers)   // new pagination format
        apiV2.GET("/users/:id", v2.GetUser) // expanded response
        apiV2.POST("/users", v2.CreateUser) // same as v1
    }
}
```

**When to bump the version:** removing a field, changing a field type, changing field meaning, changing pagination format, removing an endpoint.

**When NOT to bump:** adding a new field, adding a new endpoint, adding a new optional query param, fixing a bug.

Header versioning (`Accept: application/vnd.myapp.v2+json`) — harder to test, harder to cache. Avoid unless you have a strong reason. Query param versioning (`?version=2`) — pollutes query strings, caching nightmares. Don't use.

---

## Cursor-Based Pagination (Recommended for Large Sets)

Best for feeds, timelines, any list that changes frequently. No "page drift" problem.

```go
// GET /api/v1/orders?cursor=eyJpZCI6MTAwfQ&limit=20
type CursorQuery struct {
    Cursor string `form:"cursor"`
    Limit  int    `form:"limit" binding:"min=1,max=100"`
}

type CursorPage[T any] struct {
    Data       []T    `json:"data"`
    NextCursor string `json:"next_cursor,omitempty"` // empty = last page
    HasMore    bool   `json:"has_more"`
}

func (h *OrderHandler) List(c *gin.Context) {
    q := CursorQuery{Limit: 20}
    if err := c.ShouldBindQuery(&q); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }
    orders, nextCursor, err := h.svc.ListOrders(c.Request.Context(), q.Cursor, q.Limit)
    if err != nil {
        handleServiceError(c, err, h.logger)
        return
    }
    c.JSON(http.StatusOK, CursorPage[domain.Order]{
        Data: orders, NextCursor: nextCursor, HasMore: nextCursor != "",
    })
}
```

Cursor implementation in repository:

```go
func (r *OrderRepo) List(ctx context.Context, cursor string, limit int) ([]domain.Order, string, error) {
    var lastID int64
    if cursor != "" {
        decoded, err := base64.StdEncoding.DecodeString(cursor)
        if err != nil {
            return nil, "", fmt.Errorf("invalid cursor: %w", err)
        }
        lastID, _ = strconv.ParseInt(string(decoded), 10, 64)
    }

    var orders []domain.Order
    if err := r.db.SelectContext(ctx, &orders,
        `SELECT id, user_id, status, total, created_at FROM orders
         WHERE ($1 = 0 OR id < $1) ORDER BY id DESC LIMIT $2`,
        lastID, limit+1); err != nil {
        return nil, "", fmt.Errorf("list orders: %w", err)
    }

    var nextCursor string
    if len(orders) > limit {
        lastOrder := orders[limit]
        nextCursor = base64.StdEncoding.EncodeToString(
            []byte(strconv.FormatInt(lastOrder.ID, 10)))
        orders = orders[:limit]
    }
    return orders, nextCursor, nil
}
```

---

## Offset-Based Pagination (OK for Small Sets)

Best for admin dashboards, internal tools, data < 10K rows.

```go
// GET /api/v1/users?page=1&limit=20
type OffsetQuery struct {
    Page  int `form:"page"  binding:"min=1"`
    Limit int `form:"limit" binding:"min=1,max=100"`
}

type OffsetPage[T any] struct {
    Data       []T `json:"data"`
    Page       int `json:"page"`
    Limit      int `json:"limit"`
    TotalCount int `json:"total_count"`
    TotalPages int `json:"total_pages"`
}
```

**Warning:** `OFFSET 100000` scans 100K rows. Switch to cursor-based when data grows.

---

## Quick Decision: Which Pagination?

```
START: How many total records?
  ├── < 10K → Offset pagination is fine
  └── > 10K → Is the data frequently changing (inserts/deletes)?
      ├── No → Offset still OK (but monitor performance)
      └── Yes → Cursor-based pagination
```

---

## See Also

- `api-design-filtering-bulk-evolution.md` — filtering, sorting, bulk ops, partial updates, deprecation, backwards compatibility, error contract
brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).Stars: 322kUpdated Claude CodeCodexVerifiedInstall
brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).Stars: 198kUpdated Claude CodeCodexVerifiedInstall