Skip to content

Commit ce46f00

Browse files
authored
Merge pull request #26 from GRACENOBLE/21-feat-add-websocket-support-via-gorilla-websocket
feat(websocket): add real-time WebSocket support via gorilla/websocket
2 parents ca3564f + c5bee92 commit ce46f00

31 files changed

Lines changed: 1556 additions & 24 deletions

‎backend/.env.example‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,7 @@ FIREBASE_PROJECT_ID=
1515
# Service account key as a single-line JSON string. Get from: Firebase Console → Project Settings → Service Accounts → Generate new private key
1616
FIREBASE_SERVICE_ACCOUNT_JSON=
1717
# Sentry error tracking DSN (optional; leave empty to disable)
18-
SENTRY_DSN=
18+
SENTRY_DSN=
19+
# WebSocket allowed origin in staging/production — e.g. https://example.com
20+
# Leave empty to deny all cross-origin WebSocket connections in non-debug mode.
21+
BLUEPRINT_WS_ALLOWED_ORIGIN=http://localhost:3000

‎backend/cmd/api/main.go‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"time"
1212

1313
"backend/internal/bootstrap"
14+
"backend/internal/infrastructure/ws"
1415
"backend/internal/server"
1516
)
1617

@@ -55,7 +56,11 @@ func main() {
5556
os.Exit(1)
5657
}
5758

58-
srv := server.NewServer(app)
59+
hubCtx, hubCancel := context.WithCancel(context.Background())
60+
hub := ws.NewHub()
61+
go hub.Run(hubCtx)
62+
63+
srv := server.NewServer(app, hub)
5964
slog.Info("API docs", "url", fmt.Sprintf("http://localhost%s/swagger/index.html", srv.Addr))
6065

6166
done := make(chan bool, 1)
@@ -66,6 +71,8 @@ func main() {
6671
}
6772

6873
<-done
74+
hubCancel() // stop hub after all WS connections have been closed by server shutdown
75+
6976
if app.Cache != nil {
7077
if err := app.Cache.Close(); err != nil {
7178
slog.Error("cache close error", "error", err)

‎backend/docs/_index.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,4 @@ The `docs` agent reads this index first to locate the right file before diving i
1515
| Middleware (logger, rate limiter) | [middleware.md](middleware.md) | `internal/transport/middleware/logger.go`, `internal/transport/middleware/ratelimit.go`, `internal/transport/handlers/routes.go` |
1616
| Firebase Auth (token verification, middleware, MeHandler) | [auth.md](auth.md) | `internal/usecase/auth_usecase.go`, `internal/transport/middleware/auth.go`, `internal/transport/handlers/auth_handler.go`, `pkg/firebase/admin.go`, `internal/bootstrap/bootstrap.go` |
1717
| Observability (Sentry error tracking) | [observability.md](observability.md) | `internal/transport/middleware/sentry.go`, `internal/bootstrap/bootstrap.go`, `internal/transport/handlers/routes.go` |
18+
| WebSocket (Hub, client, GET /ws, auth, wiring) | [websocket.md](websocket.md) | `internal/infrastructure/ws/`, `internal/transport/handlers/ws_handler.go`, `internal/transport/handlers/routes.go`, `internal/server/server.go`, `cmd/api/main.go` |

‎backend/docs/routing.md‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,18 @@ sources:
1616

1717
## Handler struct
1818
```go
19-
// internal/handler/handler.go
19+
// internal/transport/handlers/handler.go
2020
type Handler struct {
2121
healthUC usecase.HealthUseCase
22+
verifier usecase.FirebaseTokenVerifier // nil disables auth (dev only)
23+
hub *ws.Hub
2224
}
2325

24-
func NewHandler(healthUC usecase.HealthUseCase) *Handler {
25-
return &Handler{healthUC: healthUC}
26+
func NewHandler(healthUC usecase.HealthUseCase, verifier usecase.FirebaseTokenVerifier, hub *ws.Hub) *Handler {
27+
return &Handler{healthUC: healthUC, verifier: verifier, hub: hub}
2628
}
2729
```
28-
The `Handler` struct holds use case interfaces — not `*sql.DB` directly. Add new use case fields here as features are added.
30+
The `Handler` struct holds use case interfaces and infrastructure dependencies — not `*sql.DB` directly. `verifier` is stored on the struct (not passed to `RegisterRoutes`) so the WebSocket handler can read it inline for query-param auth.
2931

3032
## Wiring (server.go)
3133
`internal/server/server.go` contains `NewServer(app *bootstrap.App) *http.Server` — wiring only, no logic.
@@ -34,11 +36,11 @@ It receives the already-validated `*bootstrap.App` (which holds `*sql.DB`, `Cach
3436
```go
3537
healthRepo := postgres.NewHealthRepository(app.DB)
3638
healthUC := usecase.NewHealthUseCase(healthRepo)
37-
h := handlers.NewHandler(healthUC)
39+
h := handlers.NewHandler(healthUC, app.Firebase, hub)
3840

3941
return &http.Server{
4042
Addr: fmt.Sprintf(":%d", app.Config.Port),
41-
Handler: h.RegisterRoutes(app.Config.RateLimitRPS, app.Config.RateLimitBurst, app.Firebase, app.Config.SentryDSN),
43+
Handler: h.RegisterRoutes(app.Config.RateLimitRPS, app.Config.RateLimitBurst, app.Config.SentryDSN),
4244
IdleTimeout: time.Minute,
4345
ReadTimeout: 10 * time.Second,
4446
WriteTimeout: 30 * time.Second,
@@ -51,7 +53,7 @@ All routes registered in `RegisterRoutes()` on `*Handler`, which returns `http.H
5153
`verifier` is a `usecase.FirebaseTokenVerifier`; pass `nil` to skip Firebase auth (development only — see [auth](auth.md)).
5254

5355
```go
54-
func (h *Handler) RegisterRoutes(rps float64, burst int, verifier usecase.FirebaseTokenVerifier, sentryDSN string) http.Handler {
56+
func (h *Handler) RegisterRoutes(rps float64, burst int, sentryDSN string) http.Handler {
5557
r := gin.New()
5658

5759
// Gin's colorful logger locally; structured slog logger in staging/production.
@@ -67,11 +69,13 @@ func (h *Handler) RegisterRoutes(rps float64, burst int, verifier usecase.Fireba
6769

6870
r.GET("/", h.HelloWorldHandler)
6971
r.GET("/health", h.HealthHandler)
72+
r.GET("/ws", h.WsHandler) // WebSocket upgrade — auth via ?token= query param
73+
7074
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
7175

7276
api := r.Group("/api/v1")
73-
if verifier != nil {
74-
api.Use(middleware.FirebaseAuth(verifier))
77+
if h.verifier != nil {
78+
api.Use(middleware.FirebaseAuth(h.verifier))
7579
}
7680
api.GET("/me", h.MeHandler)
7781

@@ -104,7 +108,8 @@ Allowed methods: GET, POST, PUT, DELETE, OPTIONS, PATCH.
104108
|---|---|---|---|---|
105109
| GET | `/` | none | `HelloWorldHandler` — returns `{"message": "Hello World"}` | `hello_handler.go` |
106110
| GET | `/health` | none | `HealthHandler` — returns `HealthStats`; 503 when DB is down | `health_handler.go` |
107-
| GET | `/api/v1/me` | FirebaseAuth | `MeHandler` — returns verified `FirebaseToken` claims | `auth_handler.go` |
111+
| GET | `/ws` | `?token=` query param | `WsHandler` — upgrades to WebSocket; 401 when token missing/invalid | `ws_handler.go` |
112+
| GET | `/api/v1/me` | FirebaseAuth header | `MeHandler` — returns verified `FirebaseToken` claims | `auth_handler.go` |
108113

109114
## Graceful shutdown
110115
Wired in `cmd/api/main.go` via `signal.NotifyContext` for SIGINT/SIGTERM.

‎backend/docs/swagger/docs.go‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,44 @@ const docTemplate = `{
9797
}
9898
}
9999
}
100+
},
101+
"/ws": {
102+
"get": {
103+
"description": "Upgrades HTTP to WebSocket. Pass a Firebase ID token as ` + "`" + `?token=\u003ctoken\u003e` + "`" + `. Returns 401 when the token is missing or invalid.",
104+
"produces": [
105+
"application/json"
106+
],
107+
"tags": [
108+
"websocket"
109+
],
110+
"summary": "Open a WebSocket connection",
111+
"parameters": [
112+
{
113+
"type": "string",
114+
"description": "Firebase ID token",
115+
"name": "token",
116+
"in": "query",
117+
"required": true
118+
}
119+
],
120+
"responses": {
121+
"101": {
122+
"description": "Switching Protocols",
123+
"schema": {
124+
"type": "string"
125+
}
126+
},
127+
"401": {
128+
"description": "Unauthorized",
129+
"schema": {
130+
"type": "object",
131+
"additionalProperties": {
132+
"type": "string"
133+
}
134+
}
135+
}
136+
}
137+
}
100138
}
101139
},
102140
"definitions": {

‎backend/docs/swagger/swagger.json‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,44 @@
9191
}
9292
}
9393
}
94+
},
95+
"/ws": {
96+
"get": {
97+
"description": "Upgrades HTTP to WebSocket. Pass a Firebase ID token as `?token=\u003ctoken\u003e`. Returns 401 when the token is missing or invalid.",
98+
"produces": [
99+
"application/json"
100+
],
101+
"tags": [
102+
"websocket"
103+
],
104+
"summary": "Open a WebSocket connection",
105+
"parameters": [
106+
{
107+
"type": "string",
108+
"description": "Firebase ID token",
109+
"name": "token",
110+
"in": "query",
111+
"required": true
112+
}
113+
],
114+
"responses": {
115+
"101": {
116+
"description": "Switching Protocols",
117+
"schema": {
118+
"type": "string"
119+
}
120+
},
121+
"401": {
122+
"description": "Unauthorized",
123+
"schema": {
124+
"type": "object",
125+
"additionalProperties": {
126+
"type": "string"
127+
}
128+
}
129+
}
130+
}
131+
}
94132
}
95133
},
96134
"definitions": {

‎backend/docs/swagger/swagger.yaml‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,32 @@ paths:
9797
summary: Health check
9898
tags:
9999
- ops
100+
/ws:
101+
get:
102+
description: Upgrades HTTP to WebSocket. Pass a Firebase ID token as `?token=<token>`.
103+
Returns 401 when the token is missing or invalid.
104+
parameters:
105+
- description: Firebase ID token
106+
in: query
107+
name: token
108+
required: true
109+
type: string
110+
produces:
111+
- application/json
112+
responses:
113+
"101":
114+
description: Switching Protocols
115+
schema:
116+
type: string
117+
"401":
118+
description: Unauthorized
119+
schema:
120+
additionalProperties:
121+
type: string
122+
type: object
123+
summary: Open a WebSocket connection
124+
tags:
125+
- websocket
100126
securityDefinitions:
101127
BearerAuth:
102128
description: Firebase ID token — prefix with "Bearer "

0 commit comments

Comments
 (0)