diff --git a/CHANGELOG.md b/CHANGELOG.md index cc79532..196af44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). +## [1.5.0] - 2026-09-03 + +### Added +- **Go addon parity with Node/Python** — Go now supports the same optional addon set: `--websocket` (gorilla/websocket + JWT), `--oauth` (golang.org/x/oauth2, Google + GitHub, auto-mounted at `/api/v1/oauth`), `--api-docs` (Swagger UI at `/docs` + OpenAPI JSON, auto-mounted), `--email` (stdlib `net/smtp`, no extra dependency), `--s3` (aws-sdk-go-v2, upload/presign/delete/exists, R2/MinIO via `S3_ENDPOINT`), `--queue` (asynq + Redis, including a `cmd/worker` binary), `--observability` (OpenTelemetry OTLP/HTTP tracing + Prometheus `/metrics`, plus the same `observability/` Docker Compose + Grafana dashboard stack as Node/Python), and `--sentry` (paired with `--observability`) +- **Composable Go addon wiring** — `internal/router/router.go`, `internal/config/config.go`, `go.mod`, `.env.example`, and `cmd/server/main.go` now carry `// @addon-*` splice markers so multiple Go addons (plus `jwt`) can be combined without one overwriting another's changes — the same class of bug fixed for Node in 1.4.0, addressed here before it could ship. `api-docs` and `oauth` auto-wire into `router.go` (matching what Node auto-wires into `app.ts`); the rest ship as standalone packages with next-steps instructions, mirroring Node/Python's existing split +- Patched `router.go` is passed through `gofmt` when available (best-effort; silently skipped if the `go` toolchain isn't installed) so the marker-spliced imports/routes read cleanly + +### Fixed +- **Go: Sentry no longer forces a dependency on plain `--observability` projects** — `internal/sentryinit` hard-imports `github.com/getsentry/sentry-go`, so it now ships as its own conditional addon (only alongside `--sentry`) instead of being bundled unconditionally into `--observability`; previously `go mod tidy` would add the Sentry dependency to `go.mod` even when `--sentry` was never passed, which would break `-mod=readonly` CI builds + ## [1.4.0] - 2026-07-03 ### Added diff --git a/README.md b/README.md index c15340c..b42fa6e 100644 --- a/README.md +++ b/README.md @@ -25,11 +25,12 @@ Answer a few prompts. Your project is ready in under a second. - Optional Docker + docker-compose setup - Optional testing setup with example test files - Optional GitHub Actions CI workflow -- Optional WebSocket support with Socket.io + JWT auth -- Optional OAuth2 (Google + GitHub) via `@fastify/oauth2` -- Optional API documentation via Scalar + Swagger UI -- Optional Email support via SMTP (nodemailer) — send welcome, password reset, and custom emails -- Optional S3 storage (AWS S3 / R2 / MinIO) — upload, presigned URLs, delete, exists +- Optional WebSocket support (Socket.io + JWT for Node/Python, gorilla/websocket + JWT for Go) +- Optional OAuth2 (Google + GitHub) — `@fastify/oauth2` (Node), native (Python), `golang.org/x/oauth2` (Go) +- Optional API documentation — Scalar + Swagger UI (Node/Python), Swagger UI (Go) +- Optional Email support via SMTP — nodemailer (Node), smtplib (Python), stdlib `net/smtp` (Go) +- Optional S3 storage (AWS S3 / R2 / MinIO) — upload, presigned URLs, delete, exists (all three languages) +- Optional background queue — BullMQ (Node), arq (Python), asynq + Redis (Go) - Optional Claude Code setup — `CLAUDE.md` + pre-configured skills for Claude Code agent - Optional Cursor setup — `.cursor/skills/` with pre-configured skills for Cursor agent - Optional observability stack — OpenTelemetry traces + Prometheus `/metrics` + Grafana dashboard + OTel Collector (both Node.js and Python) @@ -48,7 +49,7 @@ Answer a few prompts. Your project is ready in under a second. |----------|-------| | Node.js | TypeScript · Fastify · Prisma · MariaDB/MySQL · Redis · JWT · Zod · Pino · Swagger | | Python | FastAPI · SQLAlchemy 2.0 · Alembic · PostgreSQL · Redis · Pydantic v2 · APScheduler | -| Go | chi v5 · GORM v2 · PostgreSQL · golang-migrate · godotenv · slog · air | +| Go | chi v5 · GORM v2 · PostgreSQL · golang-migrate · godotenv · slog · air — same addon set as Node/Python (websocket, oauth, api-docs, email, s3, queue, observability) plus a Go-only `--jwt` | --- @@ -100,6 +101,13 @@ archgen add observability # OTel + Prometheus + Grafana archgen add observability --sentry # with Sentry error tracking archgen add pre-commit # pre-commit hooks (Python only: ruff + black + mypy) archgen add jwt # JWT auth addon (Go only) +archgen add websocket # WebSocket support (Go: gorilla/websocket + JWT) +archgen add oauth # OAuth2 routes (Go: golang.org/x/oauth2, Google + GitHub) +archgen add api-docs # Swagger UI at /docs + OpenAPI JSON at /openapi.json (Go) +archgen add email # SMTP email via stdlib net/smtp (Go) +archgen add s3 # S3 / R2 / MinIO storage via aws-sdk-go-v2 (Go) +archgen add queue # Background queue via asynq + Redis, plus a cmd/worker binary (Go) +archgen add observability # OTel + Prometheus for Go; add --sentry for error tracking archgen add ci --dry-run # preview changes without writing ``` diff --git a/cli/prompts.ts b/cli/prompts.ts index 43b92cd..646cb65 100644 --- a/cli/prompts.ts +++ b/cli/prompts.ts @@ -146,6 +146,13 @@ export async function promptMissingOptions( if (lang === "go") { return [ { title: "JWT authentication", value: "jwt", selected: false }, + { title: "WebSocket", value: "websocket", selected: false }, + { title: "OAuth2 (Google + GitHub)", value: "oauth", selected: false }, + { title: "API Docs (Swagger UI)", value: "apiDocs", selected: false }, + { title: "Email (SMTP)", value: "email", selected: false }, + { title: "Storage (S3 / R2 / MinIO)", value: "s3", selected: false }, + { title: "Queue (asynq + Redis)", value: "queue", selected: false }, + { title: "Observability (OTel + Prometheus)", value: "observability", selected: false }, ]; } const nodeOnly = lang === "node"; diff --git a/package.json b/package.json index e00efb2..9ac2930 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@kidkender/archgen", - "version": "1.4.0", + "version": "1.5.0", "description": "Generate production-ready Node.js, Python, and Go project structures in seconds", "main": "dist/index.js", "module": "dist/index.mjs", diff --git a/plugins/go/config.ts b/plugins/go/config.ts index 1e78629..df24c8f 100644 --- a/plugins/go/config.ts +++ b/plugins/go/config.ts @@ -3,5 +3,17 @@ import { PluginConfig } from "../../types"; export const goConfig: PluginConfig = { name: "Go", description: "Go · chi · GORM · PostgreSQL · golang-migrate · slog", - addons: ["docker", "testing", "ci", "jwt"], + addons: [ + "docker", + "testing", + "ci", + "jwt", + "websocket", + "oauth", + "api-docs", + "email", + "s3", + "queue", + "observability", + ], }; diff --git a/plugins/go/index.ts b/plugins/go/index.ts index 0971ff9..70238e3 100644 --- a/plugins/go/index.ts +++ b/plugins/go/index.ts @@ -1,8 +1,105 @@ import path from "path"; +import { execFileSync } from "child_process"; import { BasePlugin, AddonEntry } from "../../core/base-plugin"; import { TemplateVariables } from "../../core/template-engine"; -import { GenerateOptions, StackInfo } from "../../types"; +import { AddAddonOptions, GenerateOptions, StackInfo } from "../../types"; import { goConfig } from "./config"; +import { assertAddonRequires } from "../../core/addon-requires"; + +const SENTRY_REQUIRES_OBSERVABILITY_MSG = + "--sentry requires the observability addon (Sentry ships as part of it)"; + +interface GoAddonPatch { + /** Spliced into internal/router/router.go's `// @addon-imports` marker (inside the `import (...)` block). */ + routerImports?: string; + /** Spliced into internal/router/router.go's `// @addon-routes` marker (inside `New()`, before `return r`). */ + routerRoutes?: string; + /** go.mod `require (...)` entries, e.g. `module/path v1.2.3`. */ + goRequires?: (sentry: boolean) => string[]; + /** Appended to .env.example's `# @addon-env` marker. */ + env?: string; +} + +/** + * Single source of truth for addon -> router.go/go.mod/.env.example wiring, mirroring the + * Node plugin's ADDON_APP_PATCH/ADDON_ENV_PATCH/ADDON_DEPENDENCIES. Only api-docs and oauth + * auto-wire into router.go (matching what Node auto-wires into app.ts); the rest ship as + * standalone packages the generated project's README/next-steps ask the user to mount — + * same split Node/Python already use for websocket/email/s3/queue/observability. + */ +const GO_ADDON_PATCHES: Record = { + "api-docs": { + routerImports: `\t"{{MODULE_PATH}}/internal/docs"`, + routerRoutes: ['\tr.Get("/docs", docs.UI)', '\tr.Get("/openapi.json", docs.Spec)'].join("\n"), + }, + oauth: { + routerImports: `\t"{{MODULE_PATH}}/internal/oauth"`, + routerRoutes: [ + "\toauthCfg := oauth.LoadConfig()", + '\tr.Mount("/api/v1/oauth", oauth.Routes(oauthCfg))', + ].join("\n"), + goRequires: () => ["golang.org/x/oauth2 v0.24.0"], + env: [ + "APP_URL=http://localhost:8080", + "", + "# Google OAuth — https://console.cloud.google.com/", + "GOOGLE_CLIENT_ID=your-google-client-id", + "GOOGLE_CLIENT_SECRET=your-google-client-secret", + "", + "# GitHub OAuth — https://github.com/settings/developers", + "GITHUB_CLIENT_ID=your-github-client-id", + "GITHUB_CLIENT_SECRET=your-github-client-secret", + ].join("\n"), + }, + email: { + env: [ + "# Email (SMTP)", + "MAIL_HOST=smtp.gmail.com", + "MAIL_PORT=587", + "MAIL_USERNAME=your-email@gmail.com", + "MAIL_PASSWORD=your-app-password", + "MAIL_FROM_ADDRESS=your-email@gmail.com", + "MAIL_FROM_NAME={{PROJECT_NAME}}", + ].join("\n"), + }, + s3: { + goRequires: () => [ + "github.com/aws/aws-sdk-go-v2 v1.32.6", + "github.com/aws/aws-sdk-go-v2/config v1.28.6", + "github.com/aws/aws-sdk-go-v2/credentials v1.17.47", + "github.com/aws/aws-sdk-go-v2/service/s3 v1.66.3", + ], + env: [ + "# Storage (AWS S3 / Cloudflare R2 / MinIO)", + "S3_BUCKET=your-bucket-name", + "S3_REGION=us-east-1", + "# S3_ENDPOINT=https://your-r2-endpoint.r2.cloudflarestorage.com # Leave empty for AWS S3", + "AWS_ACCESS_KEY_ID=your-access-key-id", + "AWS_SECRET_ACCESS_KEY=your-secret-access-key", + ].join("\n"), + }, + websocket: { + goRequires: () => ["github.com/gorilla/websocket v1.5.3", "github.com/golang-jwt/jwt/v5 v5.2.1"], + }, + queue: { + goRequires: () => ["github.com/hibiken/asynq v0.24.1"], + env: ["# Queue (Redis)", "REDIS_ADDR=localhost:6379"].join("\n"), + }, + observability: { + goRequires: (sentry) => [ + "go.opentelemetry.io/otel v1.32.0", + "go.opentelemetry.io/otel/sdk v1.32.0", + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.32.0", + "github.com/prometheus/client_golang v1.20.5", + ...(sentry ? ["github.com/getsentry/sentry-go v0.29.1"] : []), + ], + env: ["# Observability", "OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318"].join("\n"), + }, +}; + +function substituteVars(text: string, variables: TemplateVariables): string { + return Object.entries(variables).reduce((acc, [key, value]) => acc.split(`{{${key}}}`).join(value ?? ""), text); +} export class GoPlugin extends BasePlugin { readonly name = goConfig.name; @@ -57,10 +154,76 @@ export class GoPlugin extends BasePlugin { path: path.join(addonsPath, "jwt"), label: "JWT authentication", }, + { + condition: !!options.websocket, + path: path.join(addonsPath, "websocket"), + label: "WebSocket (gorilla/websocket)", + }, + { + condition: !!options.oauth, + path: path.join(addonsPath, "oauth"), + label: "OAuth2 (Google + GitHub)", + }, + { + condition: !!options.apiDocs, + path: path.join(addonsPath, "api-docs"), + label: "API docs (Swagger UI)", + }, + { + condition: !!options.email, + path: path.join(addonsPath, "email"), + label: "Email (SMTP)", + }, + { + condition: !!options.s3, + path: path.join(addonsPath, "s3"), + label: "Storage (AWS S3)", + }, + { + condition: !!options.queue, + path: path.join(addonsPath, "queue"), + label: "Queue (asynq + Redis)", + }, + { + condition: !!options.observability, + path: path.join(addonsPath, "observability"), + label: "Observability (OTel + Prometheus)", + }, + { + // Sentry ships as its own addon dir (not bundled into observability's) because + // internal/sentryinit hard-imports github.com/getsentry/sentry-go — shipping it + // unconditionally would force that dependency on every --observability project the + // moment `go mod tidy` runs, even without --sentry. + condition: !!options.observability && !!options.sentry, + path: path.join(addonsPath, "sentry"), + label: "Sentry error tracking", + }, ]; } - protected async beforeApplyAddon(projectPath: string): Promise { + protected async beforeGenerate(_projectName: string, options: GenerateOptions): Promise { + assertAddonRequires(options.sentry, !!options.observability, SENTRY_REQUIRES_OBSERVABILITY_MSG); + } + + protected async afterGenerate(outputPath: string, options: GenerateOptions): Promise { + if (options.dryRun) return; + + const selectedAddons = [ + options.oauth && "oauth", + options.apiDocs && "api-docs", + options.email && "email", + options.s3 && "s3", + options.websocket && "websocket", + options.queue && "queue", + options.observability && "observability", + ].filter((addon): addon is string => !!addon); + + const variables = this.getVariables(path.basename(outputPath), options); + await this.patchAll(outputPath, selectedAddons, variables, !!options.sentry); + } + + protected async beforeApplyAddon(projectPath: string, addon: string, options: AddAddonOptions): Promise { + assertAddonRequires(options.sentry, addon === "observability", SENTRY_REQUIRES_OBSERVABILITY_MSG); try { const goModContent = await this.fs.readFile(path.join(projectPath, "go.mod")); const match = goModContent.match(/^module\s+(\S+)/m); @@ -70,10 +233,90 @@ export class GoPlugin extends BasePlugin { } } - protected async afterApplyAddon(): Promise { + protected async afterApplyAddon(projectPath: string, addon: string, options: AddAddonOptions): Promise { + if (!options.dryRun) { + const variables = this.buildApplyAddonVariables(path.basename(projectPath)); + + // `archgen add observability --sentry` needs the sentry addon's files too — see the + // comment on the "sentry" AddonEntry in getAddonEntries for why it's a separate dir. + if (addon === "observability" && options.sentry) { + const sentryDir = path.join(__dirname, this.relativeTemplateDir, "addons", "sentry"); + if (this.fs.exists(sentryDir)) { + await this.templateEngine.processTemplate(sentryDir, projectPath, variables, false); + } + } + + await this.patchAll(projectPath, [addon], variables, !!options.sentry); + } this._cachedModulePath = undefined; } + private async patchAll( + projectPath: string, + addons: string[], + variables: TemplateVariables, + sentry: boolean, + ): Promise { + const routerPath = path.join(projectPath, "internal", "router", "router.go"); + const envPath = path.join(projectPath, ".env.example"); + const goModPath = path.join(projectPath, "go.mod"); + + for (const addon of addons) { + const patch = GO_ADDON_PATCHES[addon]; + if (!patch) continue; + + if (patch.routerImports) { + await this.spliceMarker(routerPath, "// @addon-imports", substituteVars(patch.routerImports, variables)); + } + if (patch.routerRoutes) { + await this.spliceMarker(routerPath, "// @addon-routes", substituteVars(patch.routerRoutes, variables)); + } + if (patch.env) { + await this.spliceMarker(envPath, "# @addon-env", substituteVars(patch.env, variables)); + } + if (patch.goRequires) { + await this.mergeGoRequires(goModPath, patch.goRequires(sentry)); + } + } + + this.tryGofmt(routerPath); + } + + /** Best-effort cosmetic cleanup of the marker-spliced router.go — no-op if `gofmt` isn't on PATH. */ + private tryGofmt(filePath: string): void { + if (!this.fs.exists(filePath)) return; + try { + execFileSync("gofmt", ["-w", filePath], { stdio: "ignore" }); + } catch { + // gofmt not installed — the file still compiles, just with rougher indentation. + } + } + + /** Splices `addition` right before `marker` in the target file, skipping if already applied or the file/marker is absent. */ + private async spliceMarker(filePath: string, marker: string, addition: string): Promise { + if (!addition || !this.fs.exists(filePath)) return; + const content = await this.fs.readFile(filePath); + if (content.includes(addition)) return; + if (!content.includes(marker)) return; + await this.fs.writeFile(filePath, content.replace(marker, `${addition}\n${marker}`)); + } + + /** Adds missing `require (...)` entries to go.mod, skipping any module path already present. */ + private async mergeGoRequires(goModPath: string, deps: string[]): Promise { + if (deps.length === 0 || !this.fs.exists(goModPath)) return; + const content = await this.fs.readFile(goModPath); + + const missing = deps.filter((dep) => !content.includes(dep.trim().split(/\s+/)[0])); + if (missing.length === 0) return; + + const insertion = missing.map((dep) => `\t${dep}`).join("\n"); + const marker = "\t// @addon-requires"; + const patched = content.includes(marker) + ? content.replace(marker, `${insertion}\n${marker}`) + : content.replace(/\)\s*$/, `${insertion}\n)`); + await this.fs.writeFile(goModPath, patched); + } + protected buildApplyAddonVariables(projectName: string): TemplateVariables { return { PROJECT_NAME: projectName, @@ -114,6 +357,51 @@ export class GoPlugin extends BasePlugin { console.log(" GET /api/v1/users/me Bearer token required"); console.log(" GET /api/v1/users/{id} Bearer token required"); } + if (options.apiDocs) { + console.log(" Swagger UI available at: http://localhost:8080/docs"); + } + if (options.oauth) { + console.log(""); + console.log(" OAuth — Google + GitHub routes registered at /api/v1/oauth/*"); + console.log(" Fill in GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GITHUB_CLIENT_ID,"); + console.log(" GITHUB_CLIENT_SECRET, APP_URL in your .env file"); + } + if (options.email) { + console.log(""); + console.log(" Email (SMTP) — set MAIL_HOST/MAIL_USERNAME/MAIL_PASSWORD in your .env"); + console.log(" Use email.NewService(email.LoadConfig()) in your handlers"); + } + if (options.s3) { + console.log(""); + console.log(" Storage (S3) — set S3_BUCKET, S3_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY in .env"); + console.log(" For Cloudflare R2 / MinIO, set S3_ENDPOINT too"); + console.log(" Use storage.NewService(storage.LoadConfig()) in your handlers"); + } + if (options.websocket) { + console.log(""); + console.log(" WebSocket — mount in internal/router/router.go:"); + console.log(` hub := ws.NewHub()`); + console.log(` r.Get("/ws", ws.Handler(hub, cfg.JWTSecret))`); + } + if (options.queue) { + console.log(""); + console.log(" Queue (asynq + Redis) — set REDIS_ADDR in .env"); + console.log(" Enqueue: queue.NewClient().Enqueue(queue.NewExampleTask(...))"); + console.log(" Run worker: go run ./cmd/worker"); + } + if (options.observability) { + console.log(""); + console.log(" Observability — in cmd/server/main.go, right after cfg := config.Load():"); + console.log(` shutdown, _ := telemetry.Init("${projectName}")`); + console.log(` defer shutdown(context.Background())`); + console.log(` Mount metrics in internal/router/router.go: r.Handle("/metrics", metrics.Handler())`); + console.log(` Stack: docker compose -f observability/docker-compose.observability.yml up -d`); + if (options.sentry) { + console.log(""); + console.log(" Sentry — call defer sentryinit.Init()() in cmd/server/main.go"); + console.log(` Set SENTRY_DSN in .env`); + } + } console.log(""); } } diff --git a/plugins/go/template/addons/api-docs/internal/docs/docs.go b/plugins/go/template/addons/api-docs/internal/docs/docs.go new file mode 100644 index 0000000..ac1dc4b --- /dev/null +++ b/plugins/go/template/addons/api-docs/internal/docs/docs.go @@ -0,0 +1,54 @@ +package docs + +import ( + "encoding/json" + "net/http" +) + +const spec = `{ + "openapi": "3.0.3", + "info": { + "title": "{{PROJECT_NAME}}", + "description": "{{DESCRIPTION}}", + "version": "1.0.0" + }, + "paths": { + "/health": { + "get": { + "summary": "Health check", + "responses": { "200": { "description": "OK" } } + } + } + } +}` + +const uiPage = ` + + + {{PROJECT_NAME}} — API Docs + + + +
+ + + +` + +// Spec serves the raw OpenAPI 3.0 document. +func Spec(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + var doc map[string]interface{} + _ = json.Unmarshal([]byte(spec), &doc) + _ = json.NewEncoder(w).Encode(doc) +} + +// UI serves a Swagger UI page pointed at /openapi.json. +func UI(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + _, _ = w.Write([]byte(uiPage)) +} diff --git a/plugins/go/template/addons/email/internal/email/config.go b/plugins/go/template/addons/email/internal/email/config.go new file mode 100644 index 0000000..08640df --- /dev/null +++ b/plugins/go/template/addons/email/internal/email/config.go @@ -0,0 +1,30 @@ +package email + +import "os" + +type Config struct { + Host string + Port string + Username string + Password string + FromAddress string + FromName string +} + +func LoadConfig() *Config { + return &Config{ + Host: getEnv("MAIL_HOST", "smtp.gmail.com"), + Port: getEnv("MAIL_PORT", "587"), + Username: getEnv("MAIL_USERNAME", ""), + Password: getEnv("MAIL_PASSWORD", ""), + FromAddress: getEnv("MAIL_FROM_ADDRESS", ""), + FromName: getEnv("MAIL_FROM_NAME", "{{PROJECT_NAME}}"), + } +} + +func getEnv(key, fallback string) string { + if v := os.Getenv(key); v != "" { + return v + } + return fallback +} diff --git a/plugins/go/template/addons/email/internal/email/email.go b/plugins/go/template/addons/email/internal/email/email.go new file mode 100644 index 0000000..25eb1ed --- /dev/null +++ b/plugins/go/template/addons/email/internal/email/email.go @@ -0,0 +1,36 @@ +package email + +import ( + "fmt" + "net/smtp" +) + +type Service struct { + cfg *Config +} + +func NewService(cfg *Config) *Service { + return &Service{cfg: cfg} +} + +// Send delivers a plain-text email via SMTP (STARTTLS on the configured host/port). +func (s *Service) Send(to, subject, body string) error { + from := fmt.Sprintf("%s <%s>", s.cfg.FromName, s.cfg.FromAddress) + msg := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s\r\n", from, to, subject, body) + + auth := smtp.PlainAuth("", s.cfg.Username, s.cfg.Password, s.cfg.Host) + addr := fmt.Sprintf("%s:%s", s.cfg.Host, s.cfg.Port) + return smtp.SendMail(addr, auth, s.cfg.FromAddress, []string{to}, []byte(msg)) +} + +func (s *Service) SendWelcome(to, name string) error { + return s.Send(to, "Welcome!", fmt.Sprintf("Hi %s,\n\nWelcome aboard!", name)) +} + +func (s *Service) SendPasswordReset(to, resetLink string) error { + return s.Send(to, "Reset your password", fmt.Sprintf("Reset your password here: %s", resetLink)) +} + +func (s *Service) SendNotification(to, subject, body string) error { + return s.Send(to, subject, body) +} diff --git a/plugins/go/template/addons/jwt/go.mod b/plugins/go/template/addons/jwt/go.mod index b067cba..e649bca 100644 --- a/plugins/go/template/addons/jwt/go.mod +++ b/plugins/go/template/addons/jwt/go.mod @@ -10,4 +10,5 @@ require ( golang.org/x/crypto v0.27.0 gorm.io/driver/postgres v1.5.9 gorm.io/gorm v1.25.12 + // @addon-requires ) diff --git a/plugins/go/template/addons/jwt/internal/router/router.go b/plugins/go/template/addons/jwt/internal/router/router.go index 1722879..6f239d4 100644 --- a/plugins/go/template/addons/jwt/internal/router/router.go +++ b/plugins/go/template/addons/jwt/internal/router/router.go @@ -8,6 +8,7 @@ import ( "github.com/go-chi/chi/v5" chimw "github.com/go-chi/chi/v5/middleware" "gorm.io/gorm" + // @addon-imports ) func New(cfg *config.Config, db *gorm.DB) *chi.Mux { @@ -34,5 +35,7 @@ func New(cfg *config.Config, db *gorm.DB) *chi.Mux { }) }) + // @addon-routes + return r } diff --git a/plugins/go/template/addons/oauth/internal/oauth/config.go b/plugins/go/template/addons/oauth/internal/oauth/config.go new file mode 100644 index 0000000..cf56d40 --- /dev/null +++ b/plugins/go/template/addons/oauth/internal/oauth/config.go @@ -0,0 +1,28 @@ +package oauth + +import "os" + +type Config struct { + AppURL string + GoogleClientID string + GoogleClientSecret string + GithubClientID string + GithubClientSecret string +} + +func LoadConfig() *Config { + return &Config{ + AppURL: getEnv("APP_URL", "http://localhost:8080"), + GoogleClientID: getEnv("GOOGLE_CLIENT_ID", ""), + GoogleClientSecret: getEnv("GOOGLE_CLIENT_SECRET", ""), + GithubClientID: getEnv("GITHUB_CLIENT_ID", ""), + GithubClientSecret: getEnv("GITHUB_CLIENT_SECRET", ""), + } +} + +func getEnv(key, fallback string) string { + if v := os.Getenv(key); v != "" { + return v + } + return fallback +} diff --git a/plugins/go/template/addons/oauth/internal/oauth/oauth.go b/plugins/go/template/addons/oauth/internal/oauth/oauth.go new file mode 100644 index 0000000..c08fd31 --- /dev/null +++ b/plugins/go/template/addons/oauth/internal/oauth/oauth.go @@ -0,0 +1,104 @@ +package oauth + +import ( + "crypto/rand" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + + "github.com/go-chi/chi/v5" + "golang.org/x/oauth2" + "golang.org/x/oauth2/endpoints" +) + +func googleOAuthConfig(cfg *Config) *oauth2.Config { + return &oauth2.Config{ + ClientID: cfg.GoogleClientID, + ClientSecret: cfg.GoogleClientSecret, + Endpoint: endpoints.Google, + RedirectURL: cfg.AppURL + "/api/v1/oauth/google/callback", + Scopes: []string{"profile", "email"}, + } +} + +func githubOAuthConfig(cfg *Config) *oauth2.Config { + return &oauth2.Config{ + ClientID: cfg.GithubClientID, + ClientSecret: cfg.GithubClientSecret, + Endpoint: endpoints.GitHub, + RedirectURL: cfg.AppURL + "/api/v1/oauth/github/callback", + Scopes: []string{"user:email"}, + } +} + +func randomState() string { + b := make([]byte, 16) + _, _ = rand.Read(b) + return hex.EncodeToString(b) +} + +func fetchProfile(client *http.Client, url string) (map[string]interface{}, error) { + resp, err := client.Get(url) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + var profile map[string]interface{} + if err := json.Unmarshal(body, &profile); err != nil { + return nil, err + } + return profile, nil +} + +// Routes wires the Google + GitHub OAuth2 authorization-code flow. +// Exchanges the callback code for a token, fetches the provider profile, and +// returns it as JSON — extend this to create/log in a local user as needed. +func Routes(cfg *Config) chi.Router { + r := chi.NewRouter() + google := googleOAuthConfig(cfg) + github := githubOAuthConfig(cfg) + + r.Get("/google", func(w http.ResponseWriter, req *http.Request) { + http.Redirect(w, req, google.AuthCodeURL(randomState()), http.StatusFound) + }) + r.Get("/google/callback", func(w http.ResponseWriter, req *http.Request) { + token, err := google.Exchange(req.Context(), req.URL.Query().Get("code")) + if err != nil { + http.Error(w, fmt.Sprintf("oauth exchange failed: %v", err), http.StatusBadGateway) + return + } + profile, err := fetchProfile(google.Client(req.Context(), token), "https://www.googleapis.com/oauth2/v2/userinfo") + if err != nil { + http.Error(w, fmt.Sprintf("failed to fetch profile: %v", err), http.StatusBadGateway) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(profile) + }) + + r.Get("/github", func(w http.ResponseWriter, req *http.Request) { + http.Redirect(w, req, github.AuthCodeURL(randomState()), http.StatusFound) + }) + r.Get("/github/callback", func(w http.ResponseWriter, req *http.Request) { + token, err := github.Exchange(req.Context(), req.URL.Query().Get("code")) + if err != nil { + http.Error(w, fmt.Sprintf("oauth exchange failed: %v", err), http.StatusBadGateway) + return + } + profile, err := fetchProfile(github.Client(req.Context(), token), "https://api.github.com/user") + if err != nil { + http.Error(w, fmt.Sprintf("failed to fetch profile: %v", err), http.StatusBadGateway) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(profile) + }) + + return r +} diff --git a/plugins/go/template/addons/observability/internal/metrics/metrics.go b/plugins/go/template/addons/observability/internal/metrics/metrics.go new file mode 100644 index 0000000..ae83bdc --- /dev/null +++ b/plugins/go/template/addons/observability/internal/metrics/metrics.go @@ -0,0 +1,14 @@ +package metrics + +import ( + "net/http" + + "github.com/prometheus/client_golang/prometheus/promhttp" +) + +// Handler serves Prometheus metrics. Mount it in internal/router/router.go: +// +// r.Handle("/metrics", metrics.Handler()) +func Handler() http.Handler { + return promhttp.Handler() +} diff --git a/plugins/go/template/addons/observability/internal/telemetry/telemetry.go b/plugins/go/template/addons/observability/internal/telemetry/telemetry.go new file mode 100644 index 0000000..eb22dff --- /dev/null +++ b/plugins/go/template/addons/observability/internal/telemetry/telemetry.go @@ -0,0 +1,44 @@ +package telemetry + +import ( + "context" + "log/slog" + "os" + + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" + "go.opentelemetry.io/otel/sdk/resource" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + semconv "go.opentelemetry.io/otel/semconv/v1.26.0" +) + +// Init wires an OTLP/HTTP trace exporter (endpoint from OTEL_EXPORTER_OTLP_ENDPOINT, +// default http://localhost:4318) and registers it as the global tracer provider. +// Call the returned shutdown func before the process exits to flush pending spans. +func Init(serviceName string) (func(context.Context) error, error) { + endpoint := os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") + if endpoint == "" { + endpoint = "http://localhost:4318" + } + + exporter, err := otlptracehttp.New(context.Background(), otlptracehttp.WithEndpointURL(endpoint)) + if err != nil { + return nil, err + } + + res, err := resource.New(context.Background(), + resource.WithAttributes(semconv.ServiceName(serviceName)), + ) + if err != nil { + return nil, err + } + + tp := sdktrace.NewTracerProvider( + sdktrace.WithBatcher(exporter), + sdktrace.WithResource(res), + ) + otel.SetTracerProvider(tp) + + slog.Info("telemetry initialized", "endpoint", endpoint) + return tp.Shutdown, nil +} diff --git a/plugins/go/template/addons/observability/observability/docker-compose.observability.yml b/plugins/go/template/addons/observability/observability/docker-compose.observability.yml new file mode 100644 index 0000000..5dac5fe --- /dev/null +++ b/plugins/go/template/addons/observability/observability/docker-compose.observability.yml @@ -0,0 +1,24 @@ +services: + prometheus: + image: prom/prometheus:v2.55.1 + volumes: + - ./observability/prometheus.yml:/etc/prometheus/prometheus.yml + ports: + - "9090:9090" + + grafana: + image: grafana/grafana:11.3.1 + ports: + - "3001:3000" + environment: + GF_SECURITY_ADMIN_PASSWORD: admin + depends_on: + - prometheus + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.114.0 + command: ["--config=/etc/otel-collector.yml"] + volumes: + - ./observability/otel-collector.yml:/etc/otel-collector.yml + ports: + - "4318:4318" diff --git a/plugins/go/template/addons/observability/observability/grafana-dashboard.json b/plugins/go/template/addons/observability/observability/grafana-dashboard.json new file mode 100644 index 0000000..ad37124 --- /dev/null +++ b/plugins/go/template/addons/observability/observability/grafana-dashboard.json @@ -0,0 +1,8 @@ +{ + "title": "{{PROJECT_NAME}} — Overview", + "panels": [ + { "title": "Request rate", "type": "graph", "targets": [{ "expr": "rate(promhttp_metric_handler_requests_total[5m])" }] }, + { "title": "Active handles", "type": "graph", "targets": [{ "expr": "go_goroutines" }] } + ], + "schemaVersion": 39 +} diff --git a/plugins/go/template/addons/observability/observability/otel-collector.yml b/plugins/go/template/addons/observability/observability/otel-collector.yml new file mode 100644 index 0000000..43793e0 --- /dev/null +++ b/plugins/go/template/addons/observability/observability/otel-collector.yml @@ -0,0 +1,19 @@ +receivers: + otlp: + protocols: + http: + grpc: + +exporters: + debug: + verbosity: detailed + +processors: + batch: + +service: + pipelines: + traces: + receivers: [otlp] + processors: [batch] + exporters: [debug] diff --git a/plugins/go/template/addons/observability/observability/prometheus.yml b/plugins/go/template/addons/observability/observability/prometheus.yml new file mode 100644 index 0000000..3507bff --- /dev/null +++ b/plugins/go/template/addons/observability/observability/prometheus.yml @@ -0,0 +1,7 @@ +global: + scrape_interval: 15s + +scrape_configs: + - job_name: "{{PROJECT_NAME}}" + static_configs: + - targets: ["host.docker.internal:8080"] diff --git a/plugins/go/template/addons/queue/cmd/worker/main.go b/plugins/go/template/addons/queue/cmd/worker/main.go new file mode 100644 index 0000000..251418d --- /dev/null +++ b/plugins/go/template/addons/queue/cmd/worker/main.go @@ -0,0 +1,34 @@ +package main + +import ( + "context" + "encoding/json" + "log/slog" + + "{{MODULE_PATH}}/internal/queue" + "github.com/hibiken/asynq" +) + +func handleExampleTask(ctx context.Context, t *asynq.Task) error { + var payload queue.ExamplePayload + if err := json.Unmarshal(t.Payload(), &payload); err != nil { + return err + } + slog.Info("processed example task", "message", payload.Message) + return nil +} + +func main() { + srv := asynq.NewServer( + asynq.RedisClientOpt{Addr: queue.RedisAddr()}, + asynq.Config{Concurrency: 10}, + ) + + mux := asynq.NewServeMux() + mux.HandleFunc(queue.TaskExample, handleExampleTask) + + slog.Info("worker started") + if err := srv.Run(mux); err != nil { + slog.Error("worker stopped", "error", err) + } +} diff --git a/plugins/go/template/addons/queue/internal/queue/queue.go b/plugins/go/template/addons/queue/internal/queue/queue.go new file mode 100644 index 0000000..1e2aebf --- /dev/null +++ b/plugins/go/template/addons/queue/internal/queue/queue.go @@ -0,0 +1,35 @@ +package queue + +import ( + "encoding/json" + "os" + + "github.com/hibiken/asynq" +) + +const TaskExample = "example:task" + +func RedisAddr() string { + if v := os.Getenv("REDIS_ADDR"); v != "" { + return v + } + return "localhost:6379" +} + +func NewClient() *asynq.Client { + return asynq.NewClient(asynq.RedisClientOpt{Addr: RedisAddr()}) +} + +type ExamplePayload struct { + Message string `json:"message"` +} + +// NewExampleTask builds a task processed by the example worker +// (see cmd/worker/main.go). Enqueue it with client.Enqueue(queue.NewExampleTask(...)). +func NewExampleTask(message string) (*asynq.Task, error) { + payload, err := json.Marshal(ExamplePayload{Message: message}) + if err != nil { + return nil, err + } + return asynq.NewTask(TaskExample, payload), nil +} diff --git a/plugins/go/template/addons/s3/internal/storage/config.go b/plugins/go/template/addons/s3/internal/storage/config.go new file mode 100644 index 0000000..3e4034d --- /dev/null +++ b/plugins/go/template/addons/s3/internal/storage/config.go @@ -0,0 +1,28 @@ +package storage + +import "os" + +type Config struct { + Bucket string + Region string + Endpoint string + AccessKeyID string + SecretAccessKey string +} + +func LoadConfig() *Config { + return &Config{ + Bucket: getEnv("S3_BUCKET", ""), + Region: getEnv("S3_REGION", "us-east-1"), + Endpoint: getEnv("S3_ENDPOINT", ""), + AccessKeyID: getEnv("AWS_ACCESS_KEY_ID", ""), + SecretAccessKey: getEnv("AWS_SECRET_ACCESS_KEY", ""), + } +} + +func getEnv(key, fallback string) string { + if v := os.Getenv(key); v != "" { + return v + } + return fallback +} diff --git a/plugins/go/template/addons/s3/internal/storage/storage.go b/plugins/go/template/addons/s3/internal/storage/storage.go new file mode 100644 index 0000000..30fa233 --- /dev/null +++ b/plugins/go/template/addons/s3/internal/storage/storage.go @@ -0,0 +1,79 @@ +package storage + +import ( + "bytes" + "context" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + awsconfig "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/service/s3" +) + +type Service struct { + cfg *Config + client *s3.Client +} + +// NewService builds an S3 client. Set cfg.Endpoint for Cloudflare R2 / MinIO; +// leave it empty to talk to AWS S3 directly. +func NewService(cfg *Config) (*Service, error) { + awsCfg, err := awsconfig.LoadDefaultConfig(context.Background(), + awsconfig.WithRegion(cfg.Region), + awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(cfg.AccessKeyID, cfg.SecretAccessKey, "")), + ) + if err != nil { + return nil, err + } + + client := s3.NewFromConfig(awsCfg, func(o *s3.Options) { + if cfg.Endpoint != "" { + o.BaseEndpoint = aws.String(cfg.Endpoint) + o.UsePathStyle = true + } + }) + + return &Service{cfg: cfg, client: client}, nil +} + +func (s *Service) Upload(ctx context.Context, key string, data []byte, contentType string) error { + _, err := s.client.PutObject(ctx, &s3.PutObjectInput{ + Bucket: aws.String(s.cfg.Bucket), + Key: aws.String(key), + Body: bytes.NewReader(data), + ContentType: aws.String(contentType), + }) + return err +} + +func (s *Service) GetPresignedURL(ctx context.Context, key string, expires time.Duration) (string, error) { + presigner := s3.NewPresignClient(s.client) + req, err := presigner.PresignGetObject(ctx, &s3.GetObjectInput{ + Bucket: aws.String(s.cfg.Bucket), + Key: aws.String(key), + }, s3.WithPresignExpires(expires)) + if err != nil { + return "", err + } + return req.URL, nil +} + +func (s *Service) Delete(ctx context.Context, key string) error { + _, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{ + Bucket: aws.String(s.cfg.Bucket), + Key: aws.String(key), + }) + return err +} + +func (s *Service) Exists(ctx context.Context, key string) (bool, error) { + _, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{ + Bucket: aws.String(s.cfg.Bucket), + Key: aws.String(key), + }) + if err != nil { + return false, nil + } + return true, nil +} diff --git a/plugins/go/template/addons/sentry/internal/sentryinit/sentry.go b/plugins/go/template/addons/sentry/internal/sentryinit/sentry.go new file mode 100644 index 0000000..a8ceb1f --- /dev/null +++ b/plugins/go/template/addons/sentry/internal/sentryinit/sentry.go @@ -0,0 +1,24 @@ +package sentryinit + +import ( + "log/slog" + "os" + + "github.com/getsentry/sentry-go" +) + +// Init is a no-op unless SENTRY_DSN is set. Call it once at startup: +// +// defer sentryinit.Init()() +func Init() func() { + dsn := os.Getenv("SENTRY_DSN") + if dsn == "" { + return func() {} + } + + if err := sentry.Init(sentry.ClientOptions{Dsn: dsn}); err != nil { + slog.Error("sentry init failed", "error", err) + return func() {} + } + return func() { sentry.Flush(2e9) } +} diff --git a/plugins/go/template/addons/websocket/internal/ws/handler.go b/plugins/go/template/addons/websocket/internal/ws/handler.go new file mode 100644 index 0000000..d2f940a --- /dev/null +++ b/plugins/go/template/addons/websocket/internal/ws/handler.go @@ -0,0 +1,63 @@ +package ws + +import ( + "log/slog" + "net/http" + + "github.com/golang-jwt/jwt/v5" + "github.com/gorilla/websocket" +) + +var upgrader = websocket.Upgrader{ + ReadBufferSize: 1024, + WriteBufferSize: 1024, + // Same-origin only by default; relax this if the frontend is served + // from a different origin. + CheckOrigin: func(r *http.Request) bool { return true }, +} + +type Client struct { + conn *websocket.Conn +} + +func (c *Client) send(message []byte) { + if err := c.conn.WriteMessage(websocket.TextMessage, message); err != nil { + slog.Warn("ws write failed", "error", err) + } +} + +// Handler upgrades the request to a WebSocket connection after validating the +// `token` query param as a JWT (see internal/config JWTSecret). The claims' +// `userId` field groups connections per user for Hub.SendToUser. +func Handler(hub *Hub, jwtSecret string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + tokenStr := r.URL.Query().Get("token") + claims := jwt.MapClaims{} + _, err := jwt.ParseWithClaims(tokenStr, claims, func(t *jwt.Token) (interface{}, error) { + return []byte(jwtSecret), nil + }) + if err != nil { + http.Error(w, "invalid or missing token", http.StatusUnauthorized) + return + } + userID, _ := claims["userId"].(string) + + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + slog.Error("ws upgrade failed", "error", err) + return + } + client := &Client{conn: conn} + hub.register(userID, client) + defer func() { + hub.unregister(userID, client) + _ = conn.Close() + }() + + for { + if _, _, err := conn.ReadMessage(); err != nil { + break + } + } + } +} diff --git a/plugins/go/template/addons/websocket/internal/ws/hub.go b/plugins/go/template/addons/websocket/internal/ws/hub.go new file mode 100644 index 0000000..d4e3272 --- /dev/null +++ b/plugins/go/template/addons/websocket/internal/ws/hub.go @@ -0,0 +1,53 @@ +package ws + +import "sync" + +// Hub tracks connected clients keyed by user ID so messages can be routed +// to a specific user's connections (a user may have more than one, e.g. +// multiple browser tabs). +type Hub struct { + mu sync.RWMutex + clients map[string]map[*Client]bool +} + +func NewHub() *Hub { + return &Hub{clients: make(map[string]map[*Client]bool)} +} + +func (h *Hub) register(userID string, c *Client) { + h.mu.Lock() + defer h.mu.Unlock() + if h.clients[userID] == nil { + h.clients[userID] = make(map[*Client]bool) + } + h.clients[userID][c] = true +} + +func (h *Hub) unregister(userID string, c *Client) { + h.mu.Lock() + defer h.mu.Unlock() + delete(h.clients[userID], c) + if len(h.clients[userID]) == 0 { + delete(h.clients, userID) + } +} + +// SendToUser delivers a message to every active connection for a user. +func (h *Hub) SendToUser(userID string, message []byte) { + h.mu.RLock() + defer h.mu.RUnlock() + for c := range h.clients[userID] { + c.send(message) + } +} + +// Broadcast delivers a message to every connected client. +func (h *Hub) Broadcast(message []byte) { + h.mu.RLock() + defer h.mu.RUnlock() + for _, conns := range h.clients { + for c := range conns { + c.send(message) + } + } +} diff --git a/plugins/go/template/base/.env.example b/plugins/go/template/base/.env.example index 9e2315f..b691653 100644 --- a/plugins/go/template/base/.env.example +++ b/plugins/go/template/base/.env.example @@ -1,3 +1,4 @@ PORT=8080 DATABASE_URL=postgres://postgres:postgres@localhost:5432/{{PROJECT_NAME}}?sslmode=disable JWT_SECRET=changeme-use-a-long-random-string-in-production +# @addon-env diff --git a/plugins/go/template/base/cmd/server/main.go b/plugins/go/template/base/cmd/server/main.go index a7d56b7..95257f7 100644 --- a/plugins/go/template/base/cmd/server/main.go +++ b/plugins/go/template/base/cmd/server/main.go @@ -13,11 +13,14 @@ import ( "{{MODULE_PATH}}/internal/config" "{{MODULE_PATH}}/internal/database" "{{MODULE_PATH}}/internal/router" + // @addon-imports ) func main() { cfg := config.Load() + // @addon-init + db, err := database.Connect(cfg) if err != nil { slog.Error("failed to connect to database", "error", err) @@ -54,5 +57,6 @@ func main() { if err := srv.Shutdown(ctx); err != nil { slog.Error("server shutdown error", "error", err) } + // @addon-shutdown slog.Info("server stopped") } diff --git a/plugins/go/template/base/go.mod b/plugins/go/template/base/go.mod index 181aa05..3f5a5a7 100644 --- a/plugins/go/template/base/go.mod +++ b/plugins/go/template/base/go.mod @@ -8,4 +8,5 @@ require ( github.com/joho/godotenv v1.5.1 gorm.io/driver/postgres v1.5.9 gorm.io/gorm v1.25.12 + // @addon-requires ) diff --git a/plugins/go/template/base/internal/config/config.go b/plugins/go/template/base/internal/config/config.go index 302401b..a54f3ae 100644 --- a/plugins/go/template/base/internal/config/config.go +++ b/plugins/go/template/base/internal/config/config.go @@ -11,6 +11,7 @@ type Config struct { Port string DBUrl string JWTSecret string + // @addon-config-fields } func Load() *Config { @@ -21,6 +22,7 @@ func Load() *Config { Port: getEnv("PORT", "8080"), DBUrl: getEnv("DATABASE_URL", ""), JWTSecret: getEnv("JWT_SECRET", ""), + // @addon-config-load } } diff --git a/plugins/go/template/base/internal/router/router.go b/plugins/go/template/base/internal/router/router.go index 04fcdc5..dfa16e2 100644 --- a/plugins/go/template/base/internal/router/router.go +++ b/plugins/go/template/base/internal/router/router.go @@ -6,6 +6,7 @@ import ( "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "gorm.io/gorm" + // @addon-imports ) func New(cfg *config.Config, db *gorm.DB) *chi.Mux { @@ -19,5 +20,7 @@ func New(cfg *config.Config, db *gorm.DB) *chi.Mux { r.Get("/health", h.Health) + // @addon-routes + return r } diff --git a/tests/unit/go-plugin-addons.test.ts b/tests/unit/go-plugin-addons.test.ts new file mode 100644 index 0000000..57cc5bc --- /dev/null +++ b/tests/unit/go-plugin-addons.test.ts @@ -0,0 +1,225 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const { mockFs, mockProcessTemplate } = vi.hoisted(() => { + const mockProcessTemplate = vi.fn().mockResolvedValue([]); + const mockFs = { + exists: vi.fn().mockReturnValue(true), + removeDir: vi.fn().mockResolvedValue(undefined), + ensureDir: vi.fn().mockResolvedValue(undefined), + writeFile: vi.fn().mockResolvedValue(undefined), + readFile: vi.fn().mockResolvedValue(""), + copyFile: vi.fn().mockResolvedValue(undefined), + getAllFiles: vi.fn().mockResolvedValue([]), + }; + return { mockFs, mockProcessTemplate }; +}); + +vi.mock("../../core/file-system", () => ({ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + FileSystem: vi.fn().mockImplementation(function (this: any) { return mockFs; }), +})); + +vi.mock("../../core/template-engine", () => ({ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + TemplateEngine: vi.fn().mockImplementation(function (this: any) { + return { processTemplate: mockProcessTemplate }; + }), +})); + +import { GoPlugin } from "../../plugins/go"; +import { goConfig } from "../../plugins/go/config"; + +function addonDirsUsed(): string[] { + return mockProcessTemplate.mock.calls.map((call) => call[0] as string); +} + +describe("GoPlugin — addon parity metadata", () => { + it("lists every addon Node/Python already support (minus husky/pre-commit, which don't apply to Go)", () => { + for (const addon of ["websocket", "oauth", "api-docs", "email", "s3", "queue", "observability"]) { + expect(goConfig.addons).toContain(addon); + } + }); +}); + +describe("GoPlugin — generate() applies the right addon directories", () => { + let plugin: GoPlugin; + + beforeEach(() => { + vi.clearAllMocks(); + mockProcessTemplate.mockResolvedValue([]); + mockFs.exists.mockReturnValue(true); + mockFs.readFile.mockResolvedValue(""); + plugin = new GoPlugin(); + }); + + const cases: Array<{ flag: string; dirName: string }> = [ + { flag: "websocket", dirName: "websocket" }, + { flag: "oauth", dirName: "oauth" }, + { flag: "apiDocs", dirName: "api-docs" }, + { flag: "email", dirName: "email" }, + { flag: "s3", dirName: "s3" }, + { flag: "queue", dirName: "queue" }, + { flag: "observability", dirName: "observability" }, + ]; + + for (const { flag, dirName } of cases) { + it(`processes the "${dirName}" addon directory when --${flag} is set`, async () => { + await plugin.generate("my-app", { + language: "go", + modulePath: "github.com/acme/my-app", + outputDir: "/tmp/my-app", + [flag]: true, + }); + expect(addonDirsUsed().some((dir) => dir.endsWith(`/${dirName}`))).toBe(true); + }); + } + + it("does not process any addon directories beyond base when no flags are set", async () => { + await plugin.generate("my-app", { + language: "go", + modulePath: "github.com/acme/my-app", + outputDir: "/tmp/my-app", + }); + // Only the base template is processed (docker/testing/ci/jwt/... all condition:false). + expect(mockProcessTemplate).toHaveBeenCalledTimes(1); + }); +}); + +// ─── Regression: internal/sentryinit hard-imports github.com/getsentry/sentry-go, so it must +// never ship unless --sentry is explicitly set — otherwise `go mod tidy` forces the dependency +// on every --observability project. See the comment on the "sentry" AddonEntry in plugins/go/index.ts. + +describe("GoPlugin — sentry ships only alongside --observability --sentry", () => { + let plugin: GoPlugin; + + beforeEach(() => { + vi.clearAllMocks(); + mockProcessTemplate.mockResolvedValue([]); + mockFs.exists.mockReturnValue(true); + mockFs.readFile.mockResolvedValue(""); + plugin = new GoPlugin(); + }); + + it("generate() does NOT process the sentry addon dir when --observability is set without --sentry", async () => { + await plugin.generate("my-app", { + language: "go", + modulePath: "github.com/acme/my-app", + outputDir: "/tmp/my-app", + observability: true, + }); + expect(addonDirsUsed().some((dir) => dir.endsWith("/sentry"))).toBe(false); + }); + + it("generate() processes the sentry addon dir when both --observability and --sentry are set", async () => { + await plugin.generate("my-app", { + language: "go", + modulePath: "github.com/acme/my-app", + outputDir: "/tmp/my-app", + observability: true, + sentry: true, + }); + expect(addonDirsUsed().some((dir) => dir.endsWith("/sentry"))).toBe(true); + }); + + it("generate() throws when --sentry is set without --observability", async () => { + await expect( + plugin.generate("my-app", { + language: "go", + modulePath: "github.com/acme/my-app", + outputDir: "/tmp/my-app", + sentry: true, + }), + ).rejects.toThrow(/observability/i); + }); + + it("applyAddon() processes the sentry addon dir when adding observability with sentry:true", async () => { + await plugin.applyAddon("/tmp/my-app", "observability", { dryRun: false, sentry: true }); + expect(addonDirsUsed().some((dir) => dir.endsWith("/sentry"))).toBe(true); + }); + + it("applyAddon() does not process the sentry addon dir when adding observability without sentry", async () => { + await plugin.applyAddon("/tmp/my-app", "observability", { dryRun: false }); + expect(addonDirsUsed().some((dir) => dir.endsWith("/sentry"))).toBe(false); + }); + + it("applyAddon() throws when sentry:true and addon is not observability", async () => { + await expect( + plugin.applyAddon("/tmp/my-app", "email", { dryRun: false, sentry: true }), + ).rejects.toThrow(/observability/i); + }); +}); + +// ─── router.go marker splicing: only api-docs and oauth auto-wire into router.go. + +describe("GoPlugin — router.go marker splicing", () => { + let plugin: GoPlugin; + const baseRouter = [ + "package router", + "", + "import (", + '\t"github.com/acme/my-app/internal/config"', + "\t// @addon-imports", + ")", + "", + "func New(cfg *config.Config, db *gorm.DB) *chi.Mux {", + "\tr := chi.NewRouter()", + "", + "\t// @addon-routes", + "", + "\treturn r", + "}", + ].join("\n"); + + beforeEach(() => { + vi.clearAllMocks(); + mockProcessTemplate.mockResolvedValue([]); + mockFs.exists.mockReturnValue(true); + mockFs.readFile.mockResolvedValue(baseRouter); + plugin = new GoPlugin(); + }); + + it("splices api-docs imports/routes into router.go", async () => { + await plugin.generate("my-app", { + language: "go", + modulePath: "github.com/acme/my-app", + outputDir: "/tmp/my-app", + apiDocs: true, + }); + // The mocked readFile is stateless (always returns baseRouter), so each of the two + // spliceMarker calls (imports, then routes) re-reads the pristine content and writes + // its own patched copy — check across all router.go writes, not just the last one. + const writes = mockFs.writeFile.mock.calls + .filter(([p]: [string]) => p.endsWith("router.go")) + .map(([, content]: [string, string]) => content); + expect(writes.some((w: string) => w.includes("internal/docs"))).toBe(true); + expect(writes.some((w: string) => w.includes("docs.UI"))).toBe(true); + }); + + it("does not touch router.go for addons that don't auto-wire (e.g. email)", async () => { + await plugin.generate("my-app", { + language: "go", + modulePath: "github.com/acme/my-app", + outputDir: "/tmp/my-app", + email: true, + }); + expect(mockFs.writeFile.mock.calls.some(([p]: [string]) => p.endsWith("router.go"))).toBe(false); + }); + + it("is idempotent: re-applying an addon already fully spliced does not write again", async () => { + // applyAddon() also reads go.mod (to resolve MODULE_PATH) — the default MODULE_PATH + // fallback is github.com/example/ when go.mod can't be parsed for it, + // so the "already spliced" fixture must use that same module path. + const alreadyPatched = baseRouter + .replaceAll("github.com/acme/my-app", "github.com/example/my-app") + .replace("\t// @addon-imports", '\t"github.com/example/my-app/internal/docs"\n\t// @addon-imports') + .replace( + "\t// @addon-routes", + '\tr.Get("/docs", docs.UI)\n\tr.Get("/openapi.json", docs.Spec)\n\t// @addon-routes', + ); + mockFs.readFile.mockImplementation((p: string) => + Promise.resolve(p.endsWith("go.mod") ? "module github.com/example/my-app\n\ngo 1.22\n" : alreadyPatched), + ); + await plugin.applyAddon("/tmp/my-app", "api-docs", { dryRun: false }); + expect(mockFs.writeFile.mock.calls.some(([p]: [string]) => p.endsWith("router.go"))).toBe(false); + }); +});