go-http-api
Go HTTP API services on Fiber v3, fx, zap, GORM/PostgreSQL, Redis, Prometheus and OpenTelemetry. Use when scaffolding a Go API service, adding a resource/endpoint/feature module to one, or changing its middleware, caching, migrations, observability or Bruno collection.
- License 许可
- MIT
- 最近更新
- 2026-10-29
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- go-http-api
- description
- Go HTTP API services on Fiber v3, fx, zap, GORM/PostgreSQL, Redis, Prometheus and OpenTelemetry. Use when scaffolding a Go API service, adding a resource/endpoint/feature module to one, or changing its middleware, caching, migrations, observability or Bruno collection.
02 资源文件 14
- 参考文档references/architecture.md8.0 KB
- 参考文档references/auth.md7.4 KB
- 参考文档references/bruno.md4.5 KB
- 参考文档references/config.md3.5 KB
- 参考文档references/database.md17.2 KB
- 参考文档references/fx.md5.5 KB
- 参考文档references/http.md14.5 KB
- 参考文档references/logging.md8.4 KB
- 参考文档references/migrations.md5.4 KB
- 参考文档references/observability.md7.2 KB
- 参考文档references/openapi.md23.1 KB
- 参考文档references/redis.md11.7 KB
- 参考文档references/testing.md16.2 KB
- 参考文档references/tooling.md18.1 KB
03 SKILL.md 正文
Go HTTP API services
An opinionated stack and layout for Go HTTP APIs. The contract is written first in OpenAPI, and each feature is a self-wiring fx module. Every reference below was verified end-to-end against a running service (Go 1.27, Fiber v3.5, Postgres 18, Redis 8) in October 2026. For general Go topics (concurrency, generics, interfaces, idioms), use skill://golang-pro.
Stack
| Concern | Choice | Reference |
|---|---|---|
| Layout, layers, wiring | feature packages under internal/, generated code under gen/ |
architecture.md |
| Dependency injection | go.uber.org/fx: one Module per package |
fx.md |
| Configuration | caarlos0/env/v11, a prefix per module, injectable config.Source |
config.md |
| Logging | zap, request-scoped logger.From(ctx), GORM adapter |
logging.md |
| HTTP | Fiber v3, sonic JSON, RFC 9457 problems, admin port, graceful drain | http.md |
| Contract | OpenAPI 3.0.3, oapi-codegen strict server per tag, kin-openapi validator, keyset cursors, /v1 |
openapi.md |
| Data | GORM + PostgreSQL 18, UUIDv7, TxManager in ctx, per-feature errors | database.md |
| Schema | goose SQL migrations embedded in the binary, migrate subcommand (cobra) |
migrations.md |
| Cache, rate limit | go-redis v9, repository decorator, singleflight, fail-open; redis_rate GCRA |
redis.md |
| Metrics, traces | Prometheus client_golang; OpenTelemetry with autoexport |
observability.md |
| Tests | testify + mockery, testcontainers with a template DB, fxtest + app.Test |
testing.md |
| Build, lint, format, run | go tool, Makefile, golangci-lint v2 (lint, forbidigo stack rules, gofumpt/goimports/golines), distroless Docker, compose |
tooling.md |
| Auth (opt-in) | JWT bearer via JWKS, enforced through spec security |
auth.md |
| Manual API testing | Bruno collection generated from the spec into gen/bruno |
bruno.md |
When you change one concern in an existing service, read that row's reference and follow its rules. Check the invariants below before you finish.
Invariants
These hold in every service built with this skill. A change that breaks one is wrong even if it compiles. make lint enforces the library choices behind them with forbidigo (tooling.md): no mutexes (xsync/atomic), no logger but zap, no JSON but sonic, no os.Getenv, no global Prometheus registry, no AutoMigrate/Save, no UUIDv4, no time.Sleep.
- Contract first.
api/openapi.yamldefines every operation. The validator rejects requests that don't match it before any handler runs, so handlers never re-check shape. Handlers return only the responses the spec declares. - Generated code goes in
gen/only (gen/go/<feature>api,gen/go/httpapi,gen/go/<feature>mocks,gen/bruno). It is committed and never edited by hand. Runmake generateafter every change to the spec or to an interface. - Features wire themselves.
internal/<feature>/module.goprovides the repository, service and handler, and registers routes throughhttpserver.AsRoutes. Turning a feature on means adding<feature>.Moduletointernal/app/app.go. - Config is per module. Each module parses its own env prefix from
config.Source. Nothing callsos.Getenv. - Repositories are the only GORM users. They start every query with
tm.DB(ctx). They translategorm/pgconnerrors into the feature's sentinel errors, matching on named constraints. Services depend on theRepositoryinterface they declare themselves, and ondb.Transactor. - Errors become HTTP responses in exactly two places. Expected feature errors become typed spec responses in
handler.go. Everything else becomes a logged 500 inhttpserver.ErrorHandler. Response bodies never contain internal error text. - Log or return an error, not both. Inside a request, log through
logger.From(ctx)so every line carriesrequest_id(andtrace_idwhen spans are recorded). - Cache only through a repository decorator. Invalidate with
db.AfterCommit, bypass the cache inside transactions, and fail open. (Applies when Redis is in scope.) - Metric labels stay bounded. The route label is the template, never the raw path. No metric uses the global Prometheus registry.
- Migrations own the schema. Never call
AutoMigrate. IDs are UUIDv7, generated in Go bydb.Base. Convert timestamps with.UTC()at the DTO boundary. - Runnable as documented. From a fresh clone and a clean shell, every command in the README works as written:
make deps-up migrate-up runserves the API with no exported variables, and a missing tool, dependency or setting fails with one line naming the fix. A command that needs an undocumentedexportis a bug in the Makefile defaults, not in the docs.
Scope round
Interviews are timed (often 45 minutes), and some concerns cost build and debugging time while adding little to the discussion. Before writing any code in Workflow A, run one ask round with the four questions below in a single call, so the user can skip them explicitly. Each question has exactly these three options; every option's description says what it costs and what it buys. Recommend the timed-interview default from the table, except recommend option 0 or 1 for a concern the prompt names (caching or rate limits for Redis, observability, test strategy, deployment).
Always in scope, never asked: the OpenAPI contract and codegen, fx wiring, per-module config, zap, GORM/PostgreSQL, goose migrations, RFC 9457 problems, and the admin port with graceful drain. Auth stays opt-in: include it only if the user asks.
| Question | 0 | 1 | 2 | Timed default |
|---|---|---|---|---|
| Redis | Full: cache decorator + rate limiting | Cache only | Skip | 2 |
| Observability | Full: Prometheus + OTel, business metrics/spans where a feature warrants | Platform only: Prometheus + OTel platform code, no business metrics/spans, no Jaeger | Metrics only: no tracing | 1 |
| Tests | Full: testing.md (unit, repository, API via testcontainers) | Service unit tests with mockery only | Smoke curls only |
1 |
| Tooling | Full: lint, Docker image, full compose, Bruno | Lean: lint + dependencies-only compose | Lean + Bruno | 1 |
What each reduced choice leaves out (keep everything else as the references show it):
- Redis, Skip: no
redisx/,cache/,ratelimit/or their modules inplatform.go; noLimiterfield or limiter block inhttpserver; nocache.goorfx.Decorate(NewCachedRepository)in features; norediscompose service,REDIS_*Makefile lines or env rows; no go-redis,redis_rate,redisotelor testcontainers redis module (the testkit starts only Postgres). Cache only: keepredisx/andcache/; dropratelimit/and theLimiterwiring. - Observability, Platform only: Workflow B step 7 adds nothing; no
jaegercompose service. Metrics only: nootel/package,OTEL_*config orjaegerservice; replaceotel.Moduleinplatform.gowithfx.Provide(func() trace.TracerProvider { return noop.NewTracerProvider() })(go.opentelemetry.io/otel/trace/noop), so everytrace.TracerProviderparameter keeps compiling and log lines simply carry notrace_id. - Tests, Service unit only:
.mockery.yml,make generate-mocksand service tests against the mocks; nointernal/testkit/,main_test.go(itsTestMainneeds the testkit), testcontainers, repository or API tests, andmake testdrops itsneed-dockerprerequisite. Smoke only: no test files, no mockery tool,.mockery.yml,generate-mockstarget orgen/go/<feature>mocks. - Tooling, Lean: keep
.golangci.yml(make lintandmake fmtenforce the invariants);compose.yamlholds only Postgres (plus Redis if in scope); no Dockerfile,.dockerignore,api/migrate/jaegercompose services orcompose-up/compose-down; no Bruno: noapi/bruno/,gen/bruno/,generate-bruno,need-node,BRUNOorREDOCLY. Lean + Bruno: the same, keeping Bruno.
Record the answers as a ## Scope table in the service README (concern, choice, what adding it back takes, with the reference to follow). That table is the scope for every later change: Workflow B never adds a skipped concern, and asks again only when the request needs one. The Invariants and the verification gate apply only to concerns in scope. These reduced variants are derived from the full references, not separately verified, so the gate below is what proves them.
Workflow A: scaffold a new service
Ask for these if they're missing: the module path, the binary name, and the first feature with its operations. Then run the scope round above, and work through the steps in order, leaving out whatever the scope skipped. Each step has a done-condition; don't start the next step until it holds.
- Module, tools and Makefile (tooling.md): run
go mod init, thengo mod edit -go=1.27, then add thego get -toollines for oapi-codegen and mockery (mockery only if tests are in scope). Add the Makefile now; step 3 needsmake generate-api. With Bruno in scope, Node must be installed:make generate-brunoruns pinned tools throughnpx. Done:go tool oapi-codegen -version(andgo tool mockery version, if in scope) prints a version. - Platform packages. Create the in-scope packages of
internal/platform/{config,logger,otel,metrics,db,redisx,cache,ratelimit,admin,problem,pagination,httpserver}andplatform.go, taking the code from config.md, logging.md, observability.md, database.md, redis.md, http.md and openapi.md (validator and pagination). Leaveauth/out unless the user asked for auth. Done: every in-scope package in architecture.md's layout exists. They compile only after step 3 generatesgen/go/httpapiand addsapi/embed.go. - Contract (openapi.md): write
api/common.yaml,api/openapi.yaml(servers: /v1, the first feature's tag),api/embed.go,api/codegen/httpapi.yaml, oneapi/codegen/<feature>.yamlper tag, and, with Bruno in scope,api/bruno/environments/local.yml(bruno.md). Done:make generate-api(plusgenerate-brunowith Bruno) writesgen/go/httpapi,gen/go/<feature>api(andgen/bruno) without errors. - Entrypoint and schema (architecture.md, migrations.md): write
cmd/<binary>/main.go,internal/cli/{root,serve,migrate}.go,internal/app/app.go,migrations/embed.goand the first migration. Write that migration by hand asmigrations/<YYYYMMDDhhmmss>_create_<things>.sql://go:embed *.sqldoesn't compile with no files, somake migrationonly works once one exists. Then rungo mod tidy. Done:go build ./...succeeds. - First feature: follow Workflow B.
- Test kit (testing.md), per the Tests scope: Full writes
internal/testkit/{testkit,main}.goand.mockery.yml; Service unit only writes.mockery.yml; Smoke only skips this step. Then rungo mod tidy. - Tooling (tooling.md), per the Tooling scope:
.golangci.yml,compose.yamland.gitignorealways; the Dockerfile and.dockerignoreonly for Full. Write the README: a Run section that is exactlymake deps-up,make migrate-up,make run, the endpoints, the dev commands that exist (make generate/fmt/lint/test), the env var table (config.md), and the## Scopetable. - Verify: pass the gate below.
Workflow B: add a feature, resource or endpoint
To add an endpoint to an existing feature, run steps 1, 2 and 4 to 8 and skip whatever doesn't change. Every step follows the service README's ## Scope table.
- Spec: add the paths, tagged
<feature>, plus their schemas. List every error status each operation can return, using the shared responses fromcommon.yaml. Give request propertiesexamples so the Bruno requests are ready to send (openapi.md). - Codegen: for a new feature, copy
api/codegen/<other>.yamland changepackage,outputandinclude-tags. Then runmake generate-api(plusgenerate-brunowith Bruno). - Migration: run
make migration name=create_<things>(a service's first feature already has one from Workflow A step 4). Name every constraint, and give foreign keys noRESTRICT(migrations.md). - Feature package
internal/<feature>/(architecture.md, database.md, openapi.md):model.go: GORM model embeddingdb.Base.errors.go: sentinel errors whose messages are safe to show clients.service.go: theRepositoryinterface, input structs, andService(WithinTxfor anything that must be atomic).repository.go: a GORM implementation withtranslate.handler.go: the strict handler, with avar _ <feature>api.StrictServerInterface = (*Handler)(nil)check, aswitchmapping errors to typed responses, atoDTOthat calls.UTC(), andNewRoutes.module.go: provides the above, plusfx.Decorate(NewCachedRepository)if reads are hot and Redis is in scope (redis.md).
- Wire it: add
<feature>.Moduletointernal/app/app.go. With mocks in scope, add theRepositoryinterface to.mockery.yml, then runmake generate-mocks. - Tests (testing.md), all in
package <feature>_test, as far as the Tests scope goes (Service unit only writes just the service unit tests; Smoke only writes none):main_test.go- service unit tests for each rule
- a repository test for each translated error
- an API test per operation covering the happy path and its main error
- Metrics or spans for business events, only if the feature needs them and Observability is Full (observability.md).
- Verify: pass the gate below.
Verification gate
Work is done only when all of these hold, minus the checks for concerns the scope skipped (make test with Smoke only; the Bruno part of make generate without Bruno):
make generateleavesgit diff -- gen/limited to the changes you intended. In CI,make check-generatedpasses.make fmthas been run andmake fmt-checkexits 0 (no diff).make lintreports0 issues.make testpasses. It needs Docker for testcontainers.- Clean-shell run, after scaffolding or any change to the Makefile, config or startup: in a shell with nothing exported (
env -i HOME="$HOME" PATH="$PATH" bash), run the README's Run commands verbatim (make deps-up migrate-up run). The API must come up. Also start it once with Postgres stopped and confirm the output is a singlestartup failed: ...line. If the default ports are taken, set onlyPG_PORT/REDIS_PORT/HTTP_ADDR/ADMIN_ADDR, plusCOMPOSE_PROJECT_NAMEso you don't touch someone's running stack. - Smoke test against that running service:
curleach new or changed operation once on its happy path and once on a 4xx path. Confirm that:- 4xx responses are
application/problem+jsonwith arequest_id; curl <ADMIN_ADDR>/metricsshows the operation'sroutetemplate.
- 4xx responses are
- Drain check, after changes to the server or lifecycle: with
make runup, sendkill -TERMto the server process (the pid listening onHTTP_ADDR, e.g.lsof -ti :8080). ForHTTP_SHUTDOWN_DRAIN_DELAY,/readyzshould return 503{"status":"shutting_down"}while the API still answers. After thatmake runshould exit 0.
04 同仓库更多 Skills
unity-scriptableobjects
Architect Unity 6.3 LTS data and decoupling with ScriptableObjects: config/data assets, shared runtime variables, event channels, and runtime sets/registries. Use when designing data-driven systems, replacing singletons/managers, creating .asset data with CreateAssetMenu, or when the user mentions ScriptableObject, SO architecture, or data assets.
unity-package-management
Adds, removes, upgrades, and discovers Unity (UPM) packages from outside the Editor. Use for headless or CI package installs, verifying package IDs and versions, or choosing which packages a game needs. The Unity CLI doesn't manage packages.
unity-input-system
Wire player input in Unity 6.3 LTS with the Input System package: Input Actions, action maps, the PlayerInput component, and reading values via callbacks or polling. Use when the project has a .inputactions asset or com.unity.inputsystem, or when the user mentions the Unity Input System, InputAction, action maps, PlayerInput, control schemes, or rebinding.
unity-ecs-patterns
Master Unity ECS (Entity Component System) with DOTS, Jobs, and Burst for high-performance game development. Use when building data-oriented games, optimizing performance, or working with large entity counts.
unity-csharp-scripting
Write Unity 6.3 LTS C# gameplay scripts: the MonoBehaviour lifecycle (Awake/OnEnable/Start/Update/FixedUpdate/LateUpdate), GameObject and component access, coroutines, and Inspector serialization. Use when creating or editing .cs scripts in a Unity project, or when the user mentions MonoBehaviour, Start/Update, GetComponent, SerializeField, coroutines, or "Unity script".
unity-cli
Controls the Unity Editor and projects from the command line, driving a running Editor to edit scenes and assets or run C#. Use when asked to install or manage Editors, licenses, or projects, set up version control, build, test, configure the Unity MCP server, or run any unity command.