knit

package module
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 0 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

knit

CI Go Reference OpenSSF Scorecard

English | 日本語

knit is a lightweight, compile-time dependency injection code generator for Go, in the style of google/wire (now archived).

You list your constructors once; knit works out the order to call them in and writes plain, readable Go code that wires everything together, including cleanup functions and error handling. There is no reflection and no runtime container.

  • Native mode (default): declare injectors with knit.Build / knit.NewSet / knit.Bind. No dependency on google/wire.
  • wire mode (-mode=wire): a replacement for the wire command. It reads your existing wire.go files and writes wire_gen.go.

Install

knit requires Go 1.26 or later.

# Command-line tool
go install github.com/withnic/knit/cmd/knit@latest

# Or pin it as a tool dependency of your module and run it with `go tool knit`
go get -tool github.com/withnic/knit/cmd/knit@latest

# Marker package used in your injector declarations (native mode)
go get github.com/withnic/knit@latest

Prebuilt binaries for Linux, macOS and Windows are attached to each GitHub release.

Quick start

1. Write ordinary constructors (providers).

package app

type Store interface{ Get() string }

type SQLStore struct{ /* ... */ }

func (s *SQLStore) Get() string { /* ... */ }

func NewDSN(ctx context.Context) DSN { /* ... */ }

// A provider may return a cleanup function and/or an error.
func NewSQLStore(dsn DSN) (*SQLStore, func(), error) { /* ... */ }

func NewServer(s Store) *Server { /* ... */ }

2. Declare an injector in a file guarded by the knitinject build tag (for example knit.go). The body is a single knit.Build call listing what the injector may use.

//go:build knitinject

package app

import (
	"context"

	"github.com/withnic/knit"
)

var StoreSet = knit.NewSet(NewDSN, NewSQLStore, knit.Bind(new(Store), new(*SQLStore)))

func InitializeServer(ctx context.Context) (*Server, func(), error) {
	panic(knit.Build(StoreSet, NewServer))
}

3. Generate.

knit gen ./...

knit writes knit_gen.go next to the declaration:

// Code generated by knit. DO NOT EDIT.

//go:build !knitinject

package app

import (
	"context"
)

// Injectors from knit.go:

func InitializeServer(ctx context.Context) (*Server, func(), error) {
	var cleanups [1]func()
	cleanup := func() {
		for _, f := range cleanups {
			if f != nil {
				defer f()
			}
		}
	}
	v1 := NewDSN(ctx)
	v2, cleanupV2, err := NewSQLStore(v1)
	if err != nil {
		return nil, nil, err
	}
	cleanups[0] = cleanupV2
	v3 := NewServer(v2)
	return v3, cleanup, nil
}

4. Use it like any other function.

srv, cleanup, err := app.InitializeServer(ctx)
if err != nil {
	return err
}
defer cleanup()

Tip: add //go:generate go tool knit gen to a file in your module and regenerate with go generate ./....

Concepts

Declaration Meaning
Provider A top-level function returning (T), (T, error), (T, func()) or (T, func(), error). Its parameters are its dependencies.
knit.Build(...) Marks the enclosing function as an injector. Its parameters are inputs, its first result is the value to build, and it may also return func() and/or error.
knit.NewSet(...) Groups providers, other sets and bindings into a reusable package-level variable. Sets may be nested and may live in other packages.
knit.Bind(new(Iface), new(*Impl)) Satisfies requests for an interface with a concrete type that some provider builds.

Providers are called in dependency order, as in google/wire: starting from the injector's result, each provider's dependencies are built first, in the order of its parameters. Reorder a constructor's parameters to change the order of independent providers; their names do not matter.

If a provider fails, the cleanup functions of everything built so far run in reverse order (LIFO) before the error is returned. The cleanup returned by the injector also runs them in reverse order. A nil cleanup is skipped, and a cleanup that panics does not prevent the remaining ones from running.

Generated code is deterministic: the same input always produces byte-identical output. Errors explain the full dependency chain:

failed to resolve provider for injector 'InitializeUserService':
  service.UserService -> repo.UserRepository -> *db.Pool (provider not found)

Modes

The two modes differ only in the marker package, the build tag and the output file name. Each mode ignores the other's declarations.

knit (default) wire (-mode=wire)
Marker package github.com/withnic/knit github.com/google/wire
Declarations knit.Build / knit.NewSet / knit.Bind wire.Build / wire.NewSet / wire.Bind
Injector file tag //go:build knitinject //go:build wireinject
Generated file knit_gen.go wire_gen.go

Migrating from google/wire

Keep your injectors: run knit gen -mode=wire ./... wherever you ran wire. The output is a regular wire_gen.go. Unlike wire, knit does not copy other declarations from wire.go into the output, so move providers and anything your regular code uses to a file without the wireinject tag.

Switch to native mode:

  1. Change the build tag of your injector files from wireinject to knitinject.
  2. Replace the import github.com/google/wire with github.com/withnic/knit, and wire. with knit..
  3. Delete the old wire_gen.go files, then run knit gen ./....
  4. Run go mod tidy to drop google/wire.
Not supported

knit deliberately supports a small subset of wire. These features are rejected with an error that suggests the alternative:

wire feature Use instead
wire.Struct An explicit NewXxx constructor
wire.Value, wire.InterfaceValue A one-line ProvideXxx function
wire.FieldsOf A one-line getter function
Variadic parameters (...T) An explicit slice type ([]T) or a dedicated provider
Method or generic providers and injectors A plain top-level function
Providers declared in a file with the inject build tag Move them to a file without the tag
Unexported providers of another package Export the provider

Command reference

knit gen [flags] [packages...]   generate code (packages default to ./...)
knit version                     print the version
Flag Default Description
-mode knit knit or wire
-out knit_gen.go / wire_gen.go Name of the generated file in each package directory
-dry-run false Print the generated code instead of writing files

Exit codes: 0 success, 1 analysis or generation error, 2 usage error.

Files whose content has not changed are not rewritten. knit refuses to overwrite an output file that is not marked as generated, and reports generated files left in packages that no longer declare injectors.

Contributing

Bug reports and pull requests are welcome. Development tasks run through the Makefile (make help lists them):

make check      # go.mod tidy, formatting, lint, unit tests
make test-all   # all tests including end-to-end tests

Design documents are in docs/ (Japanese).

License

MIT

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
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Build

func Build(...any) string

Build declares an injector. It must be the only statement of the injector body, typically as panic(knit.Build(...)), and lists the providers, provider sets and bindings available to it.

Types

type Binding

type Binding struct{}

Binding binds an interface type to a concrete type.

func Bind

func Bind(iface, to any) Binding

Bind declares that every request for the interface pointed to by iface is satisfied by the concrete type pointed to by to:

knit.Bind(new(Store), new(*SQLStore))

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL