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/rate-limiting-redis.md

View on GitHub
# Rate Limiting — Redis Token Bucket & Redis Sliding Window

See also: `rate-limiting-algorithms.md`, `rate-limiting-peruser.md`, `rate-limiting-tiered.md`, `rate-limiting-headers.md`, `rate-limiting-fallback.md`

## Redis Token Bucket (Lua)

A Lua script executes atomically on the Redis instance — no race between read and write. Uses two keys per client: `tokens` (current count) and `ts` (last refill timestamp).

```go
// pkg/middleware/rate_limiter_redis.go
package middleware

import (
	"context"
	"errors"
	"log/slog"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
)

// tokenBucketScript atomically checks and decrements a token bucket stored in Redis.
// KEYS[1]: token count key, KEYS[2]: last-refill timestamp key
// ARGV[1]: capacity, ARGV[2]: refill rate (tokens/sec), ARGV[3]: current unix timestamp (float)
// Returns: remaining tokens after the request (-1 means denied).
var tokenBucketScript = redis.NewScript(`
local tokens_key = KEYS[1]
local ts_key     = KEYS[2]
local capacity   = tonumber(ARGV[1])
local rate       = tonumber(ARGV[2])
local now        = tonumber(ARGV[3])
local ttl        = math.ceil(capacity / rate) + 1

local last_ts = tonumber(redis.call("GET", ts_key))
local tokens

if last_ts == nil then
    tokens = capacity
else
    local elapsed = now - last_ts
    tokens = math.min(capacity, tonumber(redis.call("GET", tokens_key) or 0) + elapsed * rate)
end

if tokens < 1 then
    return -1
end

tokens = tokens - 1
redis.call("SETEX", tokens_key, ttl, tokens)
redis.call("SETEX", ts_key, ttl, now)
return tokens
`)

type RedisTokenBucketConfig struct {
	Client    *redis.Client
	Capacity  int
	Rate      float64
	KeyPrefix string
}

func RedisTokenBucketLimiter(cfg RedisTokenBucketConfig) gin.HandlerFunc {
	return func(c *gin.Context) {
		ctx := c.Request.Context()
		ip := c.ClientIP()
		base := cfg.KeyPrefix + ip
		tokensKey := base + ":tokens"
		tsKey := base + ":ts"
		now := float64(time.Now().UnixNano()) / 1e9

		remaining, err := tokenBucketScript.Run(ctx, cfg.Client,
			[]string{tokensKey, tsKey},
			cfg.Capacity, cfg.Rate, now,
		).Int()

		if err != nil && !errors.Is(err, redis.Nil) {
			slog.ErrorContext(ctx, "redis rate limiter error", "err", err)
			c.Next()
			return
		}

		c.Header("X-RateLimit-Limit", strconv.Itoa(cfg.Capacity))

		if remaining < 0 {
			c.Header("X-RateLimit-Remaining", "0")
			c.Header("Retry-After", strconv.Itoa(int(1.0/cfg.Rate)+1))
			c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
				"error": "rate limit exceeded",
			})
			return
		}

		c.Header("X-RateLimit-Remaining", strconv.Itoa(remaining))
		c.Next()
	}
}
```

**Why Lua:** `GET` + conditional `SET` in application code has a TOCTOU race under concurrent requests. A Lua script is executed atomically by the Redis server — no other command runs between the read and write.

See also: `rate-limiting-redis-sliding.md` for the Redis sorted-set sliding window implementation.
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