1
Fork 0
blog-go-mongo/db.go
Leonardo Devai a5937fed8d Review and modernize all 42 projects to the updated standard
Pinned 2026 toolchains (Go 1.26, Rust 1.98/edition 2024, Python 3.14 + uv, Node 24,
Zig 0.16, NixOS 26.05), postgres 18 / mongo 8, lockfiles built from, non-root
runtimes, .dockerignore, per-project LICENSE, READMEs with the git.devai.io clone
line, checkout@v7 CI. Security fixes in the legacy Rust APIs (any-password login,
self-assigned admin, hard-coded JWT secret), JWT alg/exp/sub enforcement across the
blog series, safe markdown links in the frontends, and many smaller bugs — every
project was built, run and exercised end to end.

Adds scripts/publish.sh + a CI publish job that splits every folder into its own
repo at git.devai.io/templates/<folder>.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01128fhuZbgivaSJvtMf4s1G
2026-09-27 21:10:38 +02:00

39 lines
1.2 KiB
Go

package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
// openDB connects, waits for MongoDB to answer (Ping blocks until a server is
// selectable or ctx expires), and ensures the indexes the API relies on —
// index creation is idempotent, so this is safe on every start.
func openDB(ctx context.Context, url, name string) (*mongo.Database, error) {
client, err := mongo.Connect(options.Client().ApplyURI(url))
if err != nil {
return nil, err
}
if err := client.Ping(ctx, nil); err != nil {
return nil, fmt.Errorf("ping: %w", err)
}
db := client.Database(name)
indexes := map[string]mongo.IndexModel{
"users": {Keys: bson.D{{Key: "email", Value: 1}}, Options: options.Index().SetUnique(true)},
"posts": {Keys: bson.D{{Key: "slug", Value: 1}}, Options: options.Index().SetUnique(true)},
}
for coll, model := range indexes {
if _, err := db.Collection(coll).Indexes().CreateOne(ctx, model); err != nil {
return nil, fmt.Errorf("%s index: %w", coll, err)
}
}
return db, nil
}
// isDuplicate reports whether err is a unique-index violation.
func isDuplicate(err error) bool {
return mongo.IsDuplicateKeyError(err)
}