go-backend-service
Use when building or extending a Go backend service.
- License 许可
- Unlicense
- 最近更新
- 2026-11-03
- Stars
- ★ 1
- Forks
- 0
01 前言 Front Matter
- name
- go-backend-service
- description
- Use when building or extending a Go backend service.
02 资源文件 2
- 参考文档references/golang-grpc-setup-windows.md3.8 KB
- 参考文档references/mongo-driver-v2-api.md2.5 KB
03 SKILL.md 正文
Go Backend Service (hexagonal, MongoDB, JWT, gRPC)
Covers REST + gRPC Go services with MongoDB persistence and JWT auth, built hexagonal, tested with fakes, shipped via Docker — including the user's spec-first delivery loop and the mongo-driver v2 / gRPC / Windows pitfalls.
When to use
- Building a Go service from scratch (interview challenge, Panomete business service, Deerngo-style backend)
- Adding REST/gRPC endpoints, Mongo persistence, or JWT auth to an existing Go service
- Build/test failures in a Go + MongoDB + gRPC stack
Delivery loop (user convention: spec first)
- Write the spec package first into the repo itself:
<repo>/.agents/spec/with numbered subfolders mirroringF:\projects\project_spec\template\(01_requirement, 02_design, 03_construction, 04_testing). Keep interview specs lean — 9-10 docs, no enterprise ceremony. - Resolve genuine forks with the
clarifytool before writing docs (e.g. bonus scope). One question per fork. - Implement in dependency order: scaffold → domain → application → adapters → main → tests → docker verify. Commit per phase with scoped messages.
- Module path: use
github.com/<owner>/<repo-name>; renaming later is onesedpass + proto regen (user does rename to match repo — see Pitfalls).
Architecture (hexagonal)
cmd/api/main.go # composition root: config → mongo → services → servers → worker → shutdown
internal/
domain/ # entities, validation rules, sentinel errors — STDLIB ONLY, no bson tags
application/ # use cases + ports (interfaces). No framework imports.
infrastructure/
mongodb/ # adapter implements application.UserRepository
auth/ # bcrypt hasher + HS256 JWT manager
httpapi/ # REST adapter: router, handlers, middleware, error envelope
grpcapi/ # gRPC adapter: server + JWT metadata interceptor (same core as REST)
config/ # env vars, fail-fast validation at startup
logger/ # slog JSON handler
worker/ # background jobs (ticker loops, ctx cancellation)
testutil/ # hand-written fakes (no mock library)
proto/ + gen/ # protobuf definitions + generated code (committed)
Dependency rule: domain → nothing; application → domain + ports; infrastructure → application/domain; main wires everything.
Hard-won pitfalls
- mongo-driver v2 API broke from v1 —
bson/primitiveis GONE:ObjectID,ObjectIDFromHex,NilObjectIDlive inbsondirectly.mongo.Connect(opts...)takes NO ctx. Aftergo get, rungo mod tidyor go.sum is missing transitive entries (snappy, scram, x/sync). Full map inreferences/mongo-driver-v2-api.md. - Import cycle with test doubles —
testutilimportsapplication(for port interfaces), so application tests must be EXTERNAL:package application_test+ qualify exported names. Internal tests (package application) importing testutil =import cycle not allowed in test. - Validation rules live in domain, not adapters — ObjectID shape check as regex
^[0-9a-fA-F]{24}$in domain; otherwise fake-repo tests and the Mongo adapter diverge (404 vs 400). Same for email/name rules viadomain.ValidateEmail/ValidateNamereused by create AND update paths. - grpcurl needs reflection —
reflection.Register(grpcSrv)or grpcurl cannot discover the service. Reviewers use grpcurl first. - protoc on Windows without choco/scoop — curl the win64 release zip into a gitignored
tools/protoc/; install the Go plugins withgo install. Use--go_out=. --go_opt=module=<modpath>(NOTpaths=source_relative, which dumps output undergen/proto/...). Full recipe inreferences/golang-grpc-setup-windows.md. - JWT details reviewers check — pin alg via
jwt.WithValidMethods([]string{"HS256"}); identical 401 body for wrong email AND wrong password (no user enumeration); password hash never in responses;JWT_SECRET≥32 bytes enforced at startup (fail-fast). - Go 1.22+ stdlib routing —
mux.HandleFunc("POST /api/v1/users/{id}", ...)+r.PathValue("id"); ServeMux auto-405s wrong methods. Zero web-framework deps reads as idiomatic. - Email uniqueness race — lowercase-normalize at the service boundary (create + login); pre-check FindByEmail for a friendly 409 AND unique index as the race-proof backstop (
mongo.IsDuplicateKeyError→ domain error). - Terminal guard flags
docker compose upas a server start → run it withbackground=true+ process wait; verify readiness with a separate health-poll loop.docker stopfor shutdown tests is fine. - git-bash + make —
make runmust load .env itself:set -a && . ./.env && set +a && go run ./cmd/api(single line). Long curl&&chains hit transient exit-23 pipe failures → run steps as separate commands.
Verification checklist (real tool output required, never prose-only)
go test -race -cover ./...all green; core packages ≥80% (Mongo adapter 0% is acceptable and documented as integration-only)docker compose up --build→ healthcheck 200 on both API portsbash scripts/smoke.sh→ full REST matrix passes- grpcurl:
list(reflection), authed RPC returns data, no-token →Unauthenticated - Container logs: middleware lines (method/path/status/duration_ms) + worker
total_usersticks - Graceful shutdown:
docker stop→ logs end withshutdown complete, exit code 0
Support files
references/mongo-driver-v2-api.md— v1→v2 breaking-change map + working snippetsreferences/golang-grpc-setup-windows.md— protoc install, codegen modes, reflection, bufconn test pattern
04 同仓库更多 Skills
project-spec-docs
Fill/update project_spec docs (templates, MM handoffs).
penpot-mcp
Penpot MCP: connect, verify, and fix streaming via nginx.
nginx-streaming-proxy
Configure nginx for streaming endpoints (SSE, MCP, WS).
branding-ci
Use for brand/CI identity, style guides, and brand docs.
yuanbao
Yuanbao (元宝) groups: @mention users, query info/members.
slidev
Create and present web-based slidedecks for developers using Slidev with Markdown, Vue components, code highlighting, animations, and interactive features. Use when building technical presentations, conference talks, code walkthroughs, teaching materials, or developer decks.