README
¶
di
kanna-di writes the constructor of a container struct. Each field gets its value from a provider (the function next to the field's type, or one next to the container) and the providers those need in turn, called in order in plain Go.
Part of the kanna family of code generators. Requires Go 1.26. There is nothing to import at run time: the generated code calls your own functions and nothing else.
Install
go get -tool github.com/go-kanna/di/cmd/kanna-di
Use
Take an application in layers: the domain declares a repository and a mail sender, use cases depend on them, the infrastructure implements them, and handlers call the use cases. Each layer keeps its constructors next to its types:
// package user, the domain
type Repository interface {
Save(ctx context.Context, u User) error
Find(ctx context.Context, id ID) (User, error)
}
// package mail, the domain
type Sender interface {
Send(ctx context.Context, m Message) error
}
// package usecase
func NewRegisterUser(repo user.Repository, mailer mail.Sender) *RegisterUser
func NewGetUser(repo user.Repository) *GetUser
// package postgres, the infrastructure
func NewUserRepository(db *sql.DB) *UserRepository
// package sendgrid, an external API
func NewSender(cfg config.Config) *Sender
// package handler
func NewUser(registerUser *usecase.RegisterUser, getUser *usecase.GetUser) *User
// package config
func Load() (Config, error)
The composition root already has a struct that holds what the program is made of: the server, with its handlers and
its routes. Mark it //kanna:container. What only this root can decide goes next to it: which implementation serves
each of the domain's interfaces, and how to open what the standard library provides.
package main
import (
"database/sql"
"net/http"
"example.com/shop/internal/config"
"example.com/shop/internal/handler"
_ "example.com/shop/internal/infra/postgres"
_ "example.com/shop/internal/infra/sendgrid"
"example.com/shop/internal/mail"
"example.com/shop/internal/user"
)
//go:generate go tool kanna-di
// server serves the shop's HTTP API.
//
//kanna:container
type server struct {
_ user.Repository `di:"with=postgres.NewUserRepository"`
_ mail.Sender `di:"with=sendgrid.NewSender"`
users *handler.User
}
func (s *server) routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /users", s.users.Register)
mux.HandleFunc("GET /users/{id}", s.users.Get)
return mux
}
func openDB(cfg config.Config) (*sql.DB, func(), error) {
db, err := sql.Open("pgx", cfg.DSN)
if err != nil {
return nil, nil, err
}
return db, func() { db.Close() }, nil
}
go generate ./... writes di_gen.go next to the container:
// Code generated by kanna-di. DO NOT EDIT.
package main
import (
"slices"
"example.com/shop/internal/config"
"example.com/shop/internal/handler"
"example.com/shop/internal/infra/postgres"
"example.com/shop/internal/infra/sendgrid"
"example.com/shop/internal/usecase"
)
// newServer initializes dependencies and constructs server.
func newServer() (*server, func(), error) {
cfg, err := config.Load()
if err != nil {
return nil, nil, err
}
var cleanups []func()
cleanupAll := func() {
for _, c := range slices.Backward(cleanups) {
c()
}
}
db, cleanup, err := openDB(cfg)
if err != nil {
return nil, nil, err
}
if cleanup != nil {
cleanups = append(cleanups, cleanup)
}
repo := postgres.NewUserRepository(db)
mailer := sendgrid.NewSender(cfg)
registerUser := usecase.NewRegisterUser(repo, mailer)
getUser := usecase.NewGetUser(repo)
users := handler.NewUser(registerUser, getUser)
return &server{
users: users,
}, cleanupAll, nil
}
func main() {
s, cleanup, err := newServer()
if err != nil {
log.Fatal(err)
}
defer cleanup()
log.Print(http.ListenAndServe(":8080", s.routes()))
}
*usecase.RegisterUser comes from usecase.NewRegisterUser, the function next to its type; *sql.DB from openDB,
next to the container; user.Repository and mail.Sender, the domain's interfaces, from the implementations the
container names. config.Config is loaded once, and openDB and sendgrid.NewSender share it. Nothing is registered.
When a constructor's parameters change, the next go generate changes the code that calls it.
With two or more kanna generators, run them with go tool kanna gen, which runs
them in the order they need.
Providers
A provider is a top-level function whose first result is a type declared in a package (a struct, an interface, or any other named type) or a pointer to one:
| Results | The constructor |
|---|---|
T |
|
T, error |
returns an error too, and passes this one on as is |
T, func() |
returns a cleanup too; see Cleanup |
T, func(), error |
both |
A variadic parameter ...T is passed a value of T only when the container says where one comes from: an argument
(di:"arg"), a provider it chooses (di:"with=..."), what it embeds, or, for a struct type without fields, a field of
the type. It is otherwise left empty, and no function is looked up for it, so that what a call gets is read off the
container (see Choosing a provider). A provider is called once per constructor, and everything
that needs its result shares it. A type without a name of its own, such as string, int or []byte, is never handed
out by type, since its type does not tell one value from another, a DSN from an address: a function returning one is no
provider, and neither di:"arg", with=, nor a field of a struct the container embeds serves one. Give such a value a
type of its own, such as type DSN string. A must variant beside the function it wraps, MustNewDeps beside NewDeps,
is passed over for that function, so that the error reaches the constructor instead of a panic. A generic function is no
provider either, since nothing would choose its type arguments; when nothing else provides the type, the error names the
function and says why.
For each type it needs, kanna-di takes the first of these that has one:
- an argument of the constructor (
di:"arg") - the provider the container chooses for the type (
di:"with=...") - what the container embeds: an exported field of a struct it embeds or declares as
_, or thewith=of a container it builds in place (see Containers) - the zero value, for a struct type without fields, not a pointer to one: the only value it has, which no function
needs to make, so that
newTicker(Clock{})takes it as a field of the container does (see Containers) - a function in the container's package, exported or not, or an exported function in the package declaring the type, when that package is in your module, the one whose go.mod is above the container. The functions of the two packages count together, so that one in either never hides one in the other
What the container embeds comes before any function, as embedding says what the container holds. A field added to a struct it embeds therefore serves the container from then on, in place of the function that made its type.
A go.work does not widen your module, so that a checkout without one, as CI often is, finds the same. A function of
another module of the workspace is chosen with with=, as one of any other module is.
Finding none stops generation, and so do two at the same level. The error traces the need back to the field:
$ go generate
./server.go:11:2: error: nothing provides mail.Sender, which usecase.NewRegisterUser needs
via server.users → handler.NewUser → usecase.NewRegisterUser
return one from a function in package main, take it with di:"arg", or choose a provider with di:"with=..."
./server.go:11:2: error: 2 functions in package usecase return *usecase.GetUser
usecase.NewGetUser (../../internal/usecase/get_user.go:12:6)
usecase.NewCachedGetUser (../../internal/usecase/get_user.go:30:6)
via server.users → handler.NewUser
choose one with _ *usecase.GetUser `di:"with=usecase.NewGetUser"`
./server.go:11:2: error: dependency cycle: usecase.NewRegisterUser → mail.NewWelcome → usecase.NewRegisterUser
usecase.NewRegisterUser (../../internal/usecase/register_user.go:14:6)
mail.NewWelcome (../../internal/mail/welcome.go:9:6)
via server.users → handler.NewUser
A function anywhere else is used only when the container names it. A helper in a testutil package, or a fixture
returning the same type, changes nothing about what the container gets. Nor are the standard library and other modules
searched: the only function of io that returns an io.Writer is MultiWriter, which, called with nothing, writes
nowhere. For such a type, write a function next to the container (most need configuring anyway, as sql.Open needs a
DSN) or choose one with with=.
Choosing a provider
di:"with=<ref>" chooses the provider of the field's type, for the whole container:
<ref> |
Names |
|---|---|
NewUserRepository |
a function in the container's package |
postgres.NewUserRepository |
a function of the package the container's file imports as postgres, as Go reads it in code |
Go rejects a named import nothing uses, so a package that only a with= names is imported as _, and goes by its own
name, as postgres and sendgrid do above. Nothing else is searched: a package the file does not import is an error,
with what to import.
The provider's result only has to be assignable to the type, which is how an interface gets its implementation. On a
named field, with= also stores the value; on _, it only chooses, and a struct's fields then serve the container (see
Containers).
A variadic parameter takes what with= chooses as well. A repository that kanna-orm generates takes its clock as an
option, NewOrder(db DBTX, opts ...option.Option), and a container choosing one passes it to every repository it
builds, so that which clock they use is said where they are assembled:
func clockOption() option.Option { return option.WithClock(appClock{}) }
//kanna:container
type server struct {
_ option.Option `di:"with=clockOption"`
users *handler.User
}
opts := clockOption()
orders := postgres.NewOrder(db, opts)
A container holds one value of a type, so several options are joined into one, as
option.Join(option.WithClock(appClock{}), option.WithHook(audit{})) does. For one repository to get options of its
own, write it a constructor next to the container, which takes the container's option too, and choose it:
func newOrders(db postgres.DBTX, opts ...option.Option) postgres.Order {
return postgres.NewOrder(db, append(opts, option.WithHook(audit{}))...)
}
//kanna:container
type server struct {
_ option.Option `di:"with=clockOption"`
_ postgres.Order `di:"with=newOrders"`
users *handler.User
}
A container hands out one value of a type, to everything that needs one, so two fields of a type cannot each have a
provider, or be taken as two parameters. For a primary and a replica *sql.DB, give each a type of its own, such as
type ReplicaDB struct{ *sql.DB }, with a provider returning it.
./server.go:9:2: error: package postgres has no function NewUserRepositry (field _)
did you mean NewUserRepository?
./server.go:9:2: error: postgres.NewOrderRepository returns *postgres.OrderRepository, which does not implement user.Repository (missing method Find) (field _)
Containers
//kanna:container marks a struct, and every field of it is resolved unless its tag says otherwise:
| Field | Named | _ |
|---|---|---|
| no tag | resolve the field's type and store the value | a struct with exported fields: resolve it, store nothing; else error |
di:"with=<ref>" |
resolve it with ref, which serves the type in the whole container | choose ref for the type, store nothing |
di:"arg" |
take it as a parameter, named after the field, and store it | take it as a parameter, named after its type, only |
di:"arg=<name>" |
the same, with the parameter's name spelled out | the same, with the parameter's name |
di:"-" |
leave the field alone | error |
A named or embedded field without a tag whose type is a struct with no fields, not a pointer to one, is left at its zero
value, the only value it has: a gRPC server embedding todov1.UnimplementedTodoServiceServer needs no provider for it.
A parameter named after its field or its type gives way to the imports, which keep the names of their packages, as code
written by hand does: a field config config.Config is config2 config.Config, and di:"arg=cfg" names it cfg
instead. A blank context.Context is ctx, as Go code calls one. A name spelled out keeps itself, and an import the
generated file needs under it is renamed instead; a name spelled out that the package declares at the top level, or
that Go does, is an error.
What the container takes or chooses but nothing needs draws a warning:
./server.go:12:2: warning: nothing in server needs the context.Context it takes with di:"arg"
./server.go:9:2: warning: nothing in server needs user.Repository, so its with= chooses nothing
An embedded struct, or pointer to one, is resolved (or, tagged di:"arg", taken as a parameter) and stored like any
field, and its exported fields, promoted ones included, serve the rest of the container; they cannot serve what the
struct itself is built from. A shallower field hides a deeper one of the same type, as Go hides a deeper field of the
same name; two at the same depth are an error when the type is needed.
//kanna:container
type App struct {
infra.Deps `di:"arg"` // its DB and Cache serve the providers of Users
Users *handler.User
}
A struct, or pointer to one, in a _ field serves the container the same way without being stored, so the container
gets neither the struct nor the fields and methods embedding would promote onto it. It is resolved when it, or one of
its fields, is needed: without a tag as any field is, or taken or chosen with di:"arg" or with=. A use case draws on
what the infrastructure bundles this way:
//kanna:container
type DeleteTodo struct {
_ *infra.Deps // infra.NewDeps provides it; its Transactor and Todos fill the fields below
transactor tx.Transactor
todos repository.Todo
}
func NewDeleteTodo() (*DeleteTodo, func(), error) {
var cleanups []func()
cleanupAll := func() {
for _, c := range slices.Backward(cleanups) {
c()
}
}
deps, cleanup, err := infra.NewDeps()
if err != nil {
return nil, nil, err
}
if cleanup != nil {
cleanups = append(cleanups, cleanup)
}
transactor := deps.Transactor
todos := deps.Todos
return &DeleteTodo{
transactor: transactor,
todos: todos,
}, cleanupAll, nil
}
A container of the same package embedded without a tag (a struct marked //kanna:container itself) is not built by
its own constructor but here, field by field, as part of this one. What it takes as arguments, this constructor takes
too, unless this container takes the type itself, chooses it with with=, or embeds a struct with a field of it: what
the outer container says overrides what the one it builds in place takes. Its with= serve this container after this
container's own. The value built serves whatever else in the container needs its type, wherever its field is declared.
That is how a test builds a server with some of its providers replaced, without restating it (see Tests). A
container of another package is built by its constructor instead, since its unexported fields cannot be set from here,
and so is a named field of a container type. If a container of another package keeps a value in an unexported field and
this container needs a value of that type too, generation stops with an error, since this constructor would make a
second one. To share the value, keep it in an exported field of that container, or have that container take it with
di:"arg" so this constructor passes its own; for two values, give each a type of its own.
The constructor is named after the struct: NewServer for Server, and newServer for server, so that it is
exported exactly when the struct is. A function of another name, such as one loading the configuration first, is
written by hand and calls it.
The constructor takes its parameters in the order of the fields that take them, and then those of each container it
builds in place, in the order of that container's fields. A context.Context comes first only where it is declared
first: to take ctx first, as Go code does, take it in the outer container ahead of the rest, which a container built
in place then no longer takes.
//kanna:container
type base struct {
_ context.Context `di:"arg"`
dsn DSN `di:"arg"`
}
//kanna:container
type server struct {
_ context.Context `di:"arg"` // without it, newServer(src source.Source, ctx context.Context, dsn DSN)
base
_ source.Source `di:"arg=src"`
users *handler.User
}
func newServer(ctx context.Context, src source.Source, dsn DSN) (*server, func(), error)
The directive takes options:
| Directive | Effect |
|---|---|
//kanna:container returns=<type> |
declare what the constructor returns: the struct, to return it by value, or an interface it implements (default: a pointer) |
//kanna:container must |
also write MustNewServer (mustNewServer for newServer), which panics instead of returning an error |
The must variant is written even when no provider fails, as a call of the constructor, so that the code calling it stays as providers that fail come and go.
A generic struct cannot be a container: its constructor would have no way to choose the type arguments. A struct with
di tags but no directive gets a warning, as does a misspelled directive, and one a blank line keeps from its struct,
which is then no doc comment of it. The directive on anything but a struct type, such as type Level string, a type
alias, an interface, or a function, is an error.
Write the directive against the comment marker. Go only treats //kanna:… as a directive when the two are adjacent;
with a space, // kanna:container stays part of the doc comment and shows up in go doc and on pkg.go.dev. kanna-di
does not honor that form either, and points out the spelling it expected.
Cleanup
A provider that opens something returns how to close it, and the constructor returns one cleanup for all of them:
func newServer() (*server, func(), error) {
// ...
var cleanups []func()
cleanupAll := func() {
for _, c := range slices.Backward(cleanups) {
c()
}
}
db, cleanup, err := openDB(cfg)
if err != nil {
return nil, nil, err
}
if cleanup != nil {
cleanups = append(cleanups, cleanup)
}
cache, cleanup, err := openCache(cfg)
if err != nil {
cleanupAll()
return nil, nil, err
}
if cleanup != nil {
cleanups = append(cleanups, cleanup)
}
// ...
return &server{
// ...
}, cleanupAll, nil
}
The cleanups run in the reverse of the order their providers ran in. When a provider fails, the cleanups of those that
ran before it are run before the error is returned. The must variant returns the cleanup as well. A provider with
nothing to close may return a nil cleanup. It is not called, and the cleanup the constructor returns is never nil. What
the constructor takes as an argument, or finds in a struct it embeds or declares as _, belongs to the caller and is
never closed; neither is anything for implementing io.Closer.
Tests
A container declared in a _test.go file is generated too, into di_gen_test.go next to it, in the package that file
declares (the package itself or its external _test package). This one, in the package itself, embeds the server, so
it is the server, built here with the repository and the sender taken as arguments instead of chosen with with=.
Nothing then needs *sql.DB or config.Config: openDB and config.Load are not called, and newTestServer returns
neither a cleanup nor an error.
//kanna:container
type testServer struct {
*server
_ user.Repository `di:"arg"`
_ mail.Sender `di:"arg"`
}
func TestRegisterUser(t *testing.T) {
s := newTestServer(memory.NewUserRepository(), &fakeSender{})
srv := httptest.NewServer(s.routes())
defer srv.Close()
// ...
}
What the test container takes or chooses replaces what the server takes as well as what it chooses: had the server
taken the sender with di:"arg", _ mail.Sender `di:"with=newFakeSender"` here would call newFakeSender, and
newTestServer would not take a sender.
The test calls newTestServer before the first run has written it. kanna-di type-checks the packages it loads once
more with what it is about to write in place, so a call to a constructor that is missing still, or about to take or
return something else, does not stop it. What is wrong then is reported, and nothing is written: a call the constructor
as written does not match, or a mistake the missing constructor hid, such as a method that what it returns does not
have.
The functions of a test container's package include those of its _test.go files. A provider declared in a _test.go
file is compiled into that package's tests and nowhere else, so it serves the containers of that package's tests,
in-package and external, and no other. One directory can hold test containers in either of its two test packages, not
both: they would share di_gen_test.go.
Settings of kanna-config
kanna-config writes LoadX(src source.Source) (X, error) next to each struct of
settings X, which is the function next to the type that provides X. A container of the settings takes the source as
an argument, named so that it does not give way to the import of source as source2:
//kanna:container returns=Config
type Config struct {
_ source.Source `di:"arg=src"`
API config.API
Database config.Database
}
func NewConfig(src source.Source) (Config, error) {
api, err := config.LoadAPI(src)
if err != nil {
return Config{}, err
}
database, err := config.LoadDatabase(src)
if err != nil {
return Config{}, err
}
return Config{
API: api,
Database: database,
}, nil
}
The containers that need the settings take them, as _ Config `di:"arg=cfg"`, whose fields then serve their
providers, so that config.Database reaches the function opening the database.
As with any provider, the constructor returns the error of the first LoadX that fails and calls none after it: with
both API_PORT and DATABASE_WRITER_URL wrong, it reports only API_PORT. To report every wrong setting at once,
write the function by hand in place of the container, calling each LoadX and joining their errors:
func NewConfig(src source.Source) (Config, error) {
api, errAPI := config.LoadAPI(src)
database, errDatabase := config.LoadDatabase(src)
if err := errors.Join(errAPI, errDatabase); err != nil {
return Config{}, err
}
return Config{API: api, Database: database}, nil
}
Moving from wire, fx, or dig
wire generates the code too, and its providers are functions of the same shapes: a
provider returns T, T, error, T, func(), or T, func(), error, and the constructor returns the error and one
cleanup, as an injector does. What differs is where the wiring is said:
| wire | kanna-di |
|---|---|
an injector function calling wire.Build |
a struct marked //kanna:container; the directive marks a struct, and on a function is an error |
wire.Build, wire.NewSet, and provider sets |
none: a provider is found by its type, next to the container or the type (see Providers) |
| the parameters of an injector | di:"arg" |
wire.Bind(new(I), new(*T)) |
_ I `di:"with=NewT"` |
wire.FieldsOf(new(*Deps), "DB") |
a Deps embedded, or declared as _ *Deps, whose exported fields serve the container |
wire.Value, wire.InterfaceValue |
a function next to the container returning the value |
two values of one type, such as two strings |
a type of its own for each, as in wire, but no string, int, or []byte is handed out by type at all |
A variadic parameter ...T is passed a value only when the container says where one comes from, and no function is
looked up for it (see Providers).
fx and dig register constructors at run time and call
them by reflection, so that a missing one is reported at run time. kanna-di reports it when generating, and what it
writes is the plain Go that calls the constructors, with nothing to import at run time. A value told apart by a name, as
name:"…" does in dig, is a type of its own here. There are no lifecycle hooks: main starts the server after the
constructor returns, and the cleanup closes what the providers opened.
Flags
kanna-di [flags] [packages]
| Flag | Meaning |
|---|---|
-tags <list> |
comma-separated build tags |
-check |
verify the output is up to date instead of writing it, including that no output is left over; KANNA_CHECK=1 does the same |
-v |
list the files written, removed, or left unchanged |
-deps |
print what a run reads and writes as JSON, for the kanna command, and exit |
-version |
print the version |
The packages say where the containers are, not where providers come from, and default to the one in the current
directory, so //go:generate go tool kanna-di needs no argument. A run that succeeds prints nothing but its warnings.
A package whose structs have all lost //kanna:container has its di_gen.go and di_gen_test.go removed, unless code
in the packages the run loads still calls their constructors; a file of either name without the generated-code header
is never touched. The go generate that removes one ends with open ...: no such file or directory, from go generate
itself, which lists a package's files before it runs the generators; the file is gone as it should be
(golang/go#36068).
Example
example wires a small shop in the layers above (domain, use cases, infrastructure, handlers), finding its
providers through bindings to interfaces, an argument, and an embedded container, with cleanups, a must variant, and
a test container that swaps the repository for one in memory. CI regenerates it and fails if the output would change.
Development
make test # unit tests
make lint # golangci-lint
make example # regenerate the example, then vet, test, and run it
License
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
kanna-di
command
Command kanna-di writes the constructors of structs marked //kanna:container.
|
Command kanna-di writes the constructors of structs marked //kanna:container. |
|
internal
|
|
|
gen
Package gen writes the constructors of structs marked //kanna:container.
|
Package gen writes the constructors of structs marked //kanna:container. |