Documentation
¶
Overview ¶
Package knit is the marker API for declaring injectors and provider sets for the knit code generator (https://github.com/withnic/knit).
Injectors are declared in files guarded by the knitinject build tag. Their body is a single call to Build listing the providers, provider sets and bindings the injector may use; knit gen replaces it with real code in knit_gen.go:
//go:build knitinject
package di
import "github.com/withnic/knit"
func InitializeServer(ctx context.Context) (*Server, func(), error) {
panic(knit.Build(StoreSet, NewServer))
}
var StoreSet = knit.NewSet(NewSQLStore, knit.Bind(new(Store), new(*SQLStore)))
The functions in this package only mark declarations for static analysis; they do nothing at run time.
Example ¶
package main
import (
"github.com/withnic/knit"
)
// Providers are ordinary constructors. They may also return a cleanup
// function and/or an error.
type Store interface{ Get() string }
type SQLStore struct{}
func (*SQLStore) Get() string { return "value" }
func NewSQLStore() (*SQLStore, func(), error) {
return &SQLStore{}, func() { /* close the connection */ }, nil
}
type Server struct{ Store Store }
func NewServer(s Store) *Server { return &Server{Store: s} }
// StoreSet groups providers and bindings for reuse across injectors.
var StoreSet = knit.NewSet(NewSQLStore, knit.Bind(new(Store), new(*SQLStore)))
// InitializeServer is an injector. In a real project it lives in a file
// guarded by //go:build knitinject, and `knit gen` writes its implementation
// to knit_gen.go.
func InitializeServer() (*Server, func(), error) {
panic(knit.Build(StoreSet, NewServer))
}
func main() {
// After `knit gen`, the generated InitializeServer is a regular function:
//
// srv, cleanup, err := InitializeServer()
// if err != nil {
// return err
// }
// defer cleanup()
_ = InitializeServer
}
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type ProviderSet ¶
type ProviderSet struct{}
ProviderSet is a group of providers and bindings created by NewSet.
func NewSet ¶
func NewSet(...any) ProviderSet
NewSet groups providers (functions returning (T), (T, error), (T, func()) or (T, func(), error)), other provider sets and bindings so they can be reused across injectors.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
knit
command
Command knit is a lightweight dependency injection code generator.
|
Command knit is a lightweight dependency injection code generator. |
|
internal
|
|
|
di
Package di implements knit's dependency injection code generation engine.
|
Package di implements knit's dependency injection code generation engine. |
|
graphschema
Package graphschema defines the .knit/di-graph.json format written by knit gen.
|
Package graphschema defines the .knit/di-graph.json format written by knit gen. |