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/websocket-shutdown-and-messages.md

View on GitHub
# WebSocket — Graceful Shutdown & JSON Messages

See also: `websocket-setup-and-echo.md`, `websocket-hub-and-client.md`, `websocket-auth-and-keepalive.md`, `websocket-testing.md`

## Graceful Shutdown

On server shutdown, close all WebSocket connections cleanly so clients can reconnect rather than hang.

```go
// internal/ws/hub.go — add shutdown support
type Hub struct {
    clients    map[*Client]bool
    broadcast  chan []byte
    register   chan *Client
    unregister chan *Client
    shutdown   chan struct{}
}

func NewHub() *Hub {
    return &Hub{
        clients:    make(map[*Client]bool),
        broadcast:  make(chan []byte, 256),
        register:   make(chan *Client),
        unregister: make(chan *Client),
        shutdown:   make(chan struct{}),
    }
}

func (h *Hub) Run() {
    for {
        select {
        case <-h.shutdown:
            for client := range h.clients {
                client.conn.WriteMessage(
                    websocket.CloseMessage,
                    websocket.FormatCloseMessage(websocket.CloseServiceRestart, "server shutdown"),
                )
                close(client.send)
                delete(h.clients, client)
            }
            return

        case client := <-h.register:
            h.clients[client] = true

        case client := <-h.unregister:
            if _, ok := h.clients[client]; ok {
                delete(h.clients, client)
                close(client.send)
            }

        case message := <-h.broadcast:
            for client := range h.clients {
                select {
                case client.send <- message:
                default:
                    close(client.send)
                    delete(h.clients, client)
                }
            }
        }
    }
}

func (h *Hub) Shutdown() { close(h.shutdown) }
```

Wire into server shutdown:

```go
hub := ws.NewHub()
go hub.Run()

srv := &http.Server{Addr: ":8080", Handler: r}

quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit

hub.Shutdown() // close WebSocket connections first

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
srv.Shutdown(ctx)
```

**Why close WebSocket before HTTP shutdown:** `srv.Shutdown` stops accepting new requests and waits for in-flight HTTP handlers. WebSocket handlers return immediately after spawning goroutines — those goroutines run outside Gin's request lifecycle. Shutting the hub first ensures client goroutines exit before the process terminates.

---

## JSON Messages

Use typed message envelopes with `ReadJSON`/`WriteJSON` to make the wire protocol explicit.

```go
// internal/ws/message.go
package ws

import (
    "log/slog"
    "time"

    "github.com/gorilla/websocket"
)

type MessageType string

const (
    MsgChat   MessageType = "chat"
    MsgSystem MessageType = "system"
    MsgError  MessageType = "error"
)

type Envelope struct {
    Type    MessageType `json:"type"`
    Payload any         `json:"payload"`
    SentAt  time.Time   `json:"sent_at"`
}

type ChatPayload struct {
    UserID  string `json:"user_id"`
    Content string `json:"content"`
}

func readJSON(conn *websocket.Conn, dst any) error {
    conn.SetReadDeadline(time.Now().Add(pongWait))
    return conn.ReadJSON(dst)
}

func writeJSON(conn *websocket.Conn, src any) error {
    conn.SetWriteDeadline(time.Now().Add(writeWait))
    return conn.WriteJSON(src)
}
```

**Why `any` in `Envelope.Payload`:** The envelope type is fixed, but the payload varies per message type. Unmarshal into `Envelope` first, then use `json.Unmarshal` on the re-encoded payload for strict typing:

```go
import "encoding/json"

raw, err := json.Marshal(env.Payload)
if err != nil { return }
var chat ChatPayload
if err := json.Unmarshal(raw, &chat); err != nil {
    slog.Warn("invalid chat payload", "err", err)
    return
}
```
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