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.1 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.6 KB
- 参考文档references/logging.md8.4 KB
- 参考文档references/migrations.md5.5 KB
- 参考文档references/observability.md7.2 KB
- 参考文档references/openapi.md22.9 KB
- 参考文档references/redis.md11.8 KB
- 参考文档references/testing.md16.2 KB
- 参考文档references/tooling.md18.3 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_idandtrace_id. - Cache only through a repository decorator. Invalidate with
db.AfterCommit, bypass the cache inside transactions, and fail open. - 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.
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 work through the steps in order. 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. Add the Makefile now; step 3 needsmake generate-api. Node must be installed:make generate-brunoruns pinned tools throughnpx. Done:go tool oapi-codegen -versionandgo tool mockery versionboth print a version. - Platform packages. Create
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 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, andapi/bruno/environments/local.yml(bruno.md). Done:make generate-api generate-brunowritesgen/go/httpapi,gen/go/<feature>apiandgen/brunowithout 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): write
internal/testkit/{testkit,main}.goand.mockery.yml, then rungo mod tidy. - Tooling (tooling.md): add
.golangci.yml, the Dockerfile,.dockerignore,compose.yamland.gitignore. Write the README: a Run section that is exactlymake deps-up,make migrate-up,make run, the endpoints, the dev commands (make generate/fmt/lint/test), and the env var table (config.md). - 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.
- 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 generate-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 (redis.md).
- Wire it: add
<feature>.Moduletointernal/app/app.go. Add theRepositoryinterface to.mockery.yml, then runmake generate-mocks. - Tests (testing.md), all in
package <feature>_test: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 (observability.md).
- Verify: pass the gate below.
Verification gate
Work is done only when all of these hold:
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.