skills/golang-google-wire/SKILL.md
Compile-time dependency injection in Golang using google/wire — wire.NewSet, wire.Build, wire.Bind (interface→concrete), wire.Struct, wire.Value, wire.InterfaceValue, wire.FieldsOf, cleanup functions, //go:build wireinject injector files, and generated wire_gen.go. Apply when using or adopting google/wire, when the codebase imports `github.com/google/wire`, or when wiring an application graph at compile time via `wire.Build`. For runtime DI with reflection, see `golang-uber-dig` skill.
npx skillsauth add rockcookies/skills golang-google-wireInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Persona: You are a Go architect using wire for compile-time DI. You let the compiler catch missing dependencies, treat wire_gen.go as committed source, and re-run wire ./... after every graph change.
Code-generation DI toolkit. Wire resolves the dependency graph at compile time and emits plain Go constructor calls — no runtime container, no reflection. Errors appear when you run wire ./..., not at first request.
Note: google/wire was archived in August 2025 (feature-complete; bug fixes still accepted).
Official Resources: pkg.go.dev · github.com/google/wire · User Guide · Best Practices
This skill is not exhaustive. Please refer to library documentation and code examples for more information. Context7 can help as a discoverability platform.
go get -tool github.com/google/wire/cmd/wire@latest
go get github.com/google/wire
| Concern | wire | dig / fx / samber/do |
| ----------------- | ------------------------- | ---------------------- |
| Resolution | Compile time (codegen) | Runtime (reflection) |
| Error detection | wire ./... fails | First Invoke/startup |
| Runtime container | None — plain Go calls | Present |
| Lifecycle hooks | Not built in | fx: OnStart/OnStop |
| Generated files | wire_gen.go (committed) | None |
For lifecycle, lazy loading, and a full matrix see golang-dependency-injection.
A provider is any Go function — inputs are dependencies, outputs are provided types. Three return forms:
func NewConfig() *Config { return &Config{Addr: ":8080"} }
func NewDB(cfg *Config) (*sql.DB, error) { return sql.Open("postgres", cfg.DSN) }
func NewRedis(cfg *Config) (*redis.Client, func(), error) { // cleanup chained in reverse order
c := redis.NewClient(&redis.Options{Addr: cfg.RedisAddr})
return c, func() { c.Close() }, nil
}
wire.NewSet groups providers for reuse. Sets can reference other sets.
// infra/wire.go
var InfraSet = wire.NewSet(
NewConfig,
NewDB,
NewRedis,
)
// service/wire.go
var ServiceSet = wire.NewSet(
NewUserRepo,
NewUserService,
wire.Bind(new(UserStore), new(*UserRepo)), // interface binding
)
Keep sets small: library sets expose a stable surface (adding inputs or removing outputs breaks downstream injectors). One set per package is a useful default.
//go:build wireinjectThe injector file declares the initialization function. Wire generates its body into wire_gen.go and replaces the stub.
//go:build wireinject
package main
import "github.com/google/wire"
// Wire generates the body of this function.
func InitApp() (*App, func(), error) {
wire.Build(InfraSet, ServiceSet, NewApp)
return nil, nil, nil // replaced by codegen
}
The //go:build wireinject tag prevents the stub from being compiled into the binary — only wire_gen.go (which has no such tag) makes it through go build. Without this tag, both files define the same function, causing a compile error.
Alternative syntax when a dummy return is inconvenient:
func InitApp() (*App, func(), error) {
panic(wire.Build(InfraSet, ServiceSet, NewApp))
}
Wire forbids implicit interface satisfaction — you must declare bindings explicitly so the graph is unambiguous when multiple types implement the same interface.
var Set = wire.NewSet(
NewPostgresUserRepo,
wire.Bind(new(UserStore), new(*PostgresUserRepo)), // tell wire: *PostgresUserRepo satisfies UserStore
)
Explicit bindings prevent graph breakage when a new type implementing the same interface is added elsewhere.
wire.Struct fills struct fields from the graph without a manual constructor. Tag fields wire:"-" to exclude them.
wire.Struct(new(Server), "Logger", "DB") // inject named fields
wire.Struct(new(Server), "*") // inject all non-excluded fields
wire.Value(Foo{X: 42}) // constant expression (no fn calls / channels)
wire.InterfaceValue(new(io.Reader), os.Stdin) // interface-typed literal
wire.FieldsOf(new(Config), "DSN", "Addr") // promote struct fields as graph nodes
See advanced.md for the wire:"-" exclusion tag and wire.FieldsOf details.
Wire forbids two providers for the same type. Wrap the underlying type in distinct named types so each has exactly one provider:
type PrimaryDSN string
type ReplicaDSN string
// wire.go — injector, excluded from binary via build tag
//go:build wireinject
package main
func InitApp() (*App, func(), error) {
wire.Build(config.ConfigSet, infra.InfraSet, service.ServiceSet, NewApp)
return nil, nil, nil
}
// main.go
func main() {
app, cleanup, err := InitApp()
if err != nil { log.Fatal(err) }
defer cleanup()
app.Run()
}
Wire generates wire_gen.go (plain Go, committed, DO NOT EDIT). For a full example with per-package sets, cleanup-heavy graphs, and generated output, see recipes.md.
wire ./... # regenerate all injectors in the module
wire check ./... # validate graph without regenerating (fast CI check)
Run wire ./... after every constructor signature change. Add //go:generate go run github.com/google/wire/cmd/wire to injector files so go generate ./... also works. Commit wire_gen.go — it must stay in sync for CI builds.
wire_gen.go — it is overwritten on every wire ./... run. Treat it as a build artifact that happens to be committed; source of truth is the provider and injector files.//go:build wireinject to injector files — omitting it causes duplicate-symbol compile errors because both the stub and the generated file define the same function.type DSN string let you have PrimaryDSN and ReplicaDSN coexist.(T, func(), error) from cleanup providers and let wire chain them — wire generates the correct reverse-order cleanup and handles partial failures (if construction fails midway, only already-built cleanups run).wire.Build arguments are hard to reason about; delegate to per-package sets.| Mistake | Fix |
| --- | --- |
| Editing wire_gen.go manually | Never edit it. Change providers or injectors and re-run wire ./.... |
| Missing //go:build wireinject | Add the tag as the very first line of every injector file. |
| Two providers returning *sql.DB | Wrap with a named struct type: type PrimaryDB struct { *sql.DB } — Wire does not distinguish pointer type aliases. |
| Injecting an interface without wire.Bind | Add wire.Bind(new(MyInterface), new(*MyImpl)) to the provider set. |
| Forgetting to re-run wire ./... after changes | Run wire before go build; add it to go generate or a Makefile target. |
| Calling cleanup() without guarding for nil | Wire returns nil cleanup on construction error; guard with if cleanup != nil { defer cleanup() }. |
Wire generates plain Go constructors, so unit tests use manual injection — no container to clone or reset. For testing patterns (test injectors swapping real providers for fakes, CI stale-check for wire_gen.go), see testing.md.
golang-dependency-injection skill for DI concepts and library comparisongolang-uber-dig skill for runtime reflection-based DI without lifecyclegolang-uber-fx skill for runtime DI with lifecycle hooks, modules, and signal-aware Run()golang-samber-do skill for generics-based DI without reflectiongolang-structs-interfaces skill for interface design patternsgolang-testing skill for general testing patternsIf you encounter a bug or unexpected behavior in google/wire, open an issue at https://github.com/google/wire/issues.
development
Vue 3 debugging and error handling for runtime errors, warnings, async failures, and SSR/hydration issues. Use when diagnosing or fixing Vue issues.
development
MUST be used for Vue.js tasks. Strongly recommends Composition API with `<script setup>` and TypeScript as the standard approach. Covers Vue 3, SSR, Volar, vue-tsc. Load for any Vue, .vue files, Vue Router, Pinia, or Vite with Vue work. ALWAYS use Composition API unless the project explicitly requires Options API.
development
GORM Gen 类型安全 DAO 代码生成,基于 github.com/rockcookies/go-gen(rockcookies fork)。涵盖代码生成配置、模型生成、查询构建、增删改查、关联关系、动态 SQL 注解、事务处理、datatypes 自定义字段类型(JSON/JSONMap/JSONSlice/JSONType/Date/UUID)、soft_delete 软删除插件(unix 时间戳/flag 模式),以及 fork 专有功能:Tmpl 运行时模板覆写(18 个模板)、Unsafe 底层方法(UnsafeSetDB/Alias/ModelType/TableName)、IGenericsDo[T,E] 泛型接口。使用时机:需要从数据库生成 DAO 代码(GenerateModel/GenerateModelAs)、编写 DAL 查询(DO 链式调用、DaoScope、事务、关联加载)、配置生成器(gen.Config、ModelOpt、FieldGORMTag、FieldModify、FieldType、Tmpl 自定义模板)、使用 datatypes(JSONMap、JSONSlice、JSONQuery、JSONSet)或 soft_delete(DeletedAt、softDelete:milli、deleteOpts)时使用本技能。当用户消息中包含以下任一关键词(go-gen、gorm-gen、GenerateModelAs、ModelOpt、FieldGORMTag、FieldModify、DaoScope、LoadOneToMany、LoadManyToMany、IGenericsDo、UnsafeSetDB、datatypes、JSONMap、JSONSlice、JSONQuery、soft_delete、softDelete、DeletedAt),或用户明确请求 GORM Gen 代码生成/DAO 编写时触发本技能。
development
轻量级 Go HTTP 客户端库,基于 github.com/rockcookies/go-fetch(零外部依赖)。涵盖 Dispatcher 初始化与中间件、Request 链式构建(RequestFunc 与 Middleware 分层)、Response 解码(JSON/XML/流)、请求体编码(JSON/XML/Form/Multipart/BodyGet)、URL 参数(PrepareURLMiddleware/URLOptions)、Header/Cookie 管理(ApplyHeader/ApplyCookie 与 Context)、中间件组合(Dispatcher/Request/Do 三层)、HTTP 交换日志(dump.New/dump.Transport/过滤器/WithRequestRedactor/WithResponseRedactor/SlogWriter)。使用时机:需要发起 HTTP 请求(GET/POST/PUT/PATCH/DELETE,均需 context.Context)、上传文件(Multipart/GetReader)、配置全局认证头(dispatcher.Use)、记录 HTTP 交换日志(dump.New、WithFilter、DefaultRedactor)、构建可复用的请求基础(Request.Clone)时使用本技能。当用户消息中包含以下任一关键词(go-fetch、NewDispatcher、NewDispatcherWithTransport、RequestFunc、PreFuncs、UseFuncs、BodyGet、MultipartField、dump.New、WithFilter、WithRequestRedactor、WithResponseRedactor、DefaultRedactor、DumpOptions、SlogWriter、URLOptions、PrepareURLMiddleware、PathParams、SetURLOptions、WithURLOptions、ApplyHeader、SetHeaderOptions、WithHeaderOptions、ApplyCookie、SetCookieOptions、WithCookieOptions、HandlerFunc、fetch.Handler、fetch.Middleware、dispatcher.Use、resp.Close、resp.JSON、resp.XML),或用户明确请求 go-fetch HTTP 客户端用法时触发本技能。