interactor

package module
v3.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 7 Imported by: 1 module, 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

Interactor

codecov Go Vulnerabilities Release Go Version Go Reference License

Interactor runs use cases and dispatches requests to them by request type. It is inspired by Uncle Bob's Clean Architecture and the interactor concept described there.

A use case is any type with a Run method from a request to a response. The compiler checks the types, and the use case is called directly: reflection is only used to look it up by request type and to reject a nil one, never to call it.

Installation

Requires Go 1.27 or later.

go get github.com/screwyprof/interactor/v3@latest

Usage

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/screwyprof/interactor/v3"
)

type Hello struct{ Name string }

type Greeting struct{ Text string }

// Greet is a use case: a type with a Run method from a request to a response.
type Greet struct{}

func (Greet) Run(ctx context.Context, req Hello) (Greeting, error) {
	return Greeting{Text: "Hello, " + req.Name + "!"}, nil
}

func main() {
	var d interactor.Dispatcher
	d.MustRegister(Greet{})

	greeting, err := d.Dispatch[Greeting](context.Background(), Hello{Name: "Gopher"})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(greeting.Text) // Hello, Gopher!
}
  • MustRegister panics on a wiring mistake, which is what you want at startup; Register returns the error instead.
  • Dispatch names only the response type; the request type is inferred from the argument.
  • A plain function becomes a use case with interactor.UseCaseFunc[Hello, Greeting](fn).
  • The zero Dispatcher is ready to use and safe for concurrent use; don't copy it after first use.
  • The use case is found by the request's static type, so pass the concrete request type, not one held in any.
  • Request types match exactly: Hello and *Hello are different types.
Dispatcher or a single use case?

The Dispatcher gives a component one dependency through which it runs many use cases:

type Handler struct {
	uc *interactor.Dispatcher
}

func (h Handler) Checkout(ctx context.Context, cart Cart) (Receipt, error) {
	order, err := h.uc.Dispatch[Order](ctx, PlaceOrder{Cart: cart})
	if err != nil {
		return Receipt{}, err
	}

	return h.uc.Dispatch[Receipt](ctx, ChargeOrder{OrderID: order.ID})
}

In tests, register fake use cases on a real Dispatcher; no mock is needed.

A component that runs a single use case can depend on it directly, since UseCase is a plain interface: greet interactor.UseCase[Hello, Greeting], then h.greet.Run(ctx, req).

Errors

They come back wrapped with the types involved in the message, so match them with errors.Is, not ==.

Error When
ErrAlreadyRegistered Register for a request type that already has a use case (MustRegister panics with it)
ErrNilUseCase Register with a nil use case (MustRegister panics with it)
ErrUseCaseNotFound Dispatch for a request type nothing is registered for
ErrResponseTypeMismatch Dispatch asks for a response type other than the registered use case's

Errors returned by the use case itself come back unchanged. The context is passed to the use case as given.

Testing your use cases

Use cases are plain types, so any testing style works. The testdsl package is there if you want each test to read as a scenario: given this use case, when it runs with this request, then expect this.

import "github.com/screwyprof/interactor/v3/testdsl"

func TestGreet(t *testing.T) {
	testdsl.Test(t).
		Given(Greet{}).
		When(t.Context(), Hello{Name: "Gopher"}).
		Then(Greeting{Text: "Hello, Gopher!"})
}

Given fixes the use case's request and response types for the rest of the chain, so When only accepts its request and Then only its response: Then(42) would not compile.

Expect an error with ThenFailWith, which matches like errors.Is. Say Greet rejects an empty name with ErrNoName:

func TestGreetRejectsAnEmptyName(t *testing.T) {
	testdsl.Test(t).
		Given(Greet{}).
		When(t.Context(), Hello{}).
		ThenFailWith(ErrNoName)
}

For anything else, ThenCheck hands you the typed result:

func TestGreetMentionsTheName(t *testing.T) {
	testdsl.Test(t).
		Given(Greet{}).
		When(t.Context(), Hello{Name: "Gopher"}).
		ThenCheck(func(tb testing.TB, got Greeting, err error) {
			require.NoError(tb, err)
			assert.Contains(tb, got.Text, "Gopher")
		})
}

Scenarios fit table-driven tests too:

func TestGreetScenarios(t *testing.T) {
	tests := map[string]struct {
		when Hello
		then func(*testdsl.When[Greeting])
	}{
		"greets by name": {
			when: Hello{Name: "Gopher"},
			then: func(w *testdsl.When[Greeting]) { w.Then(Greeting{Text: "Hello, Gopher!"}) },
		},
		"rejects empty names": {
			when: Hello{},
			then: func(w *testdsl.When[Greeting]) { w.ThenFailWith(ErrNoName) },
		},
	}

	for name, tc := range tests {
		t.Run(name, func(t *testing.T) {
			tc.then(testdsl.Test(t).Given(Greet{}).When(t.Context(), tc.when))
		})
	}
}

When takes the context the use case runs under, usually t.Context(), or one carrying values such as the current user. As with any assertion library, a scenario checks only what it asks for, so end each one with a Then method. testdsl uses testify, so your tests depend on it too.

Migrating from v2

v3 replaces the reflection-based API with generics. Most of what v2 checked at runtime is now a compile error.

v2 v3
Run(ctx, req Req, res *Res) error Run(ctx, req Req) (Res, error); to move one use case at a time, wrap the old shape (below)
UseCaseRunner, UseCaseRunnerFn UseCase[Req, Res], UseCaseFunc[Req, Res]
code depending on UseCaseRunner to accept the dispatcher *interactor.Dispatcher, or an interface you define for the use case you need: a generic method can't satisfy an interface, so the dispatcher no longer implements one
interactor.NewDispatcher() var d interactor.Dispatcher
d.Register(Req{}, interactor.MustAdapt(uc)) d.MustRegister(uc); a nil *T is still rejected at registration
d.Register(Req{}, interactor.Must(interactor.Func(fn))) d.MustRegister(interactor.UseCaseFunc[Req, Res](fn))
var res Res; err := d.Run(ctx, req, &res) res, err := d.Dispatch[Res](ctx, req)
a request held in any was routed by its dynamic type routing uses the static type: pass the concrete request
registering a type twice overwrote the first ErrAlreadyRegistered, and MustRegister panics
a nil runner failed at Run with ErrUseCaseRunnerNotFound ErrNilUseCase at Register
ErrUseCaseRunnerNotFound ErrUseCaseNotFound
ErrResultTypeMismatch ErrResponseTypeMismatch
Request, Response, Func, Adapt, Must, MustAdapt and their runtime errors (ErrRequestTypeMismatch, ErrInvalidReturnType, …) removed: the compiler checks what they checked at runtime
ErrNilContext removed: a nil context reaches the use case, as in any Go call
testdsl.Test(t)(Given(r), When(ctx, req, &res), Then(want)) and its InteractorTester, GivenFn, WhenFn, ThenFn, Checker types testdsl.Test(t).Given(uc).When(ctx, req).Then(want), checked at compile time; When takes the context as before but no &res; ThenFailWith(err) now needs a non-nil error and stops the test on a mismatch

To move one use case at a time, wrap a v2-style Run in a UseCaseFunc and register that:

d.MustRegister(interactor.UseCaseFunc[Req, Res](func(ctx context.Context, req Req) (Res, error) {
	var res Res
	err := legacy.Run(ctx, req, &res)

	return res, err
}))

The wrapper is yours to adjust. As written it returns whatever the legacy code wrote to res, even alongside an error, and starts each call from a zero res, so it never sees values a v2 caller filled in beforehand. If legacy is a pointer, check it is not nil before wrapping legacy.Run: the dispatcher can only see the wrapper.

Documentation

pkg.go.dev/github.com/screwyprof/interactor/v3

Contributing

Contributions are welcome. See CONTRIBUTING.md: make check runs the same gates as CI, and a fix needs a test that fails without it.

License

Released under the MIT License.

Documentation

Overview

Package interactor runs use cases and dispatches requests to them by request type.

A use case is any type with a Run method taking a request and returning a response:

type Greet struct{}

func (Greet) Run(ctx context.Context, req Hello) (Greeting, error) { ... }

Register it on a Dispatcher, then dispatch requests of that type:

var d interactor.Dispatcher
d.MustRegister(Greet{}) // or Register, to handle the error

greeting, err := d.Dispatch[Greeting](ctx, Hello{Name: "Gopher"})

Types are checked by the compiler; only the wiring (a request type nobody registered, or a response type other than the registered one) is checked when dispatching.

Example
package main

import (
	"context"
	"fmt"

	"github.com/screwyprof/interactor/v3"
)

type Hello struct{ Name string }

type Greeting struct{ Text string }

// Greet is a use case: a type with a Run method from a request to a response.
type Greet struct{}

func (Greet) Run(_ context.Context, req Hello) (Greeting, error) {
	return Greeting{Text: "Hello, " + req.Name + "!"}, nil
}

func main() {
	var d interactor.Dispatcher

	d.MustRegister(Greet{})

	greeting, err := d.Dispatch[Greeting](context.Background(), Hello{Name: "Gopher"})
	if err != nil {
		fmt.Println(err)

		return
	}

	fmt.Println(greeting.Text)

}
Output:
Hello, Gopher!

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrUseCaseNotFound      = errors.New("interactor: no use case registered for request type")
	ErrAlreadyRegistered    = errors.New("interactor: use case already registered for request type")
	ErrNilUseCase           = errors.New("interactor: use case must not be nil")
	ErrResponseTypeMismatch = errors.New("interactor: registered use case returns a different response type")
)

Errors returned by Dispatcher.Register and Dispatcher.Dispatch. They come back wrapped with the types involved, so match them with errors.Is.

Functions

This section is empty.

Types

type Dispatcher

type Dispatcher struct {
	// contains filtered or unexported fields
}

Dispatcher routes a request to the use case registered for its type.

The zero value is ready to use. A Dispatcher is safe for concurrent use and must not be copied after first use.

func (*Dispatcher) Dispatch

func (d *Dispatcher) Dispatch[Res, Req any](ctx context.Context, req Req) (Res, error)

Dispatch runs the use case registered for req's type and returns its response.

Res comes first so callers name only the response type and the request type is inferred:

greeting, err := d.Dispatch[Greeting](ctx, Hello{})

The use case is found by Req, the request's static type: a request held in an interface variable is looked up as that interface type, not its dynamic type. Res must be exactly the registered use case's response type.

It returns an error wrapping ErrUseCaseNotFound if nothing is registered for Req, or ErrResponseTypeMismatch if the registered use case returns a type other than Res. ctx is passed to the use case as given. Errors from the use case itself are returned unchanged, including any it gets from dispatching further requests, together with whatever response it returned alongside the error.

Example (NotFound)
package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/screwyprof/interactor/v3"
)

type Hello struct{ Name string }

type Greeting struct{ Text string }

func main() {
	var d interactor.Dispatcher

	_, err := d.Dispatch[Greeting](context.Background(), Hello{Name: "Gopher"})

	fmt.Println(errors.Is(err, interactor.ErrUseCaseNotFound))

}
Output:
true

func (*Dispatcher) MustRegister

func (d *Dispatcher) MustRegister[Req, Res any](uc UseCase[Req, Res])

MustRegister is like Dispatcher.Register but panics if registration fails. Use it when wiring an application at startup, where a duplicate or nil use case is a programming mistake.

func (*Dispatcher) Register

func (d *Dispatcher) Register[Req, Res any](uc UseCase[Req, Res]) error

Register adds uc as the use case for requests of type Req.

Request types match exactly: Req and *Req are different types. For a nil use case the error wraps ErrNilUseCase, and if Req already has one it wraps ErrAlreadyRegistered; both name the request type.

Register is meant for wiring at startup: each call copies the registrations, so that Dispatch can read them without locking.

Example
package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/screwyprof/interactor/v3"
)

type Hello struct{ Name string }

type Greeting struct{ Text string }

// Greet is a use case: a type with a Run method from a request to a response.
type Greet struct{}

func (Greet) Run(_ context.Context, req Hello) (Greeting, error) {
	return Greeting{Text: "Hello, " + req.Name + "!"}, nil
}

func main() {
	var d interactor.Dispatcher

	d.MustRegister(Greet{})

	// Register returns the error instead, for wiring that is decided at runtime.
	err := d.Register(Greet{})

	fmt.Println(errors.Is(err, interactor.ErrAlreadyRegistered))

}
Output:
true

type UseCase

type UseCase[Req, Res any] interface {
	Run(ctx context.Context, req Req) (Res, error)
}

UseCase handles one request type and returns its response.

type UseCaseFunc

type UseCaseFunc[Req, Res any] func(ctx context.Context, req Req) (Res, error)

UseCaseFunc lets a plain function be a UseCase, like net/http.HandlerFunc.

Example
package main

import (
	"context"
	"fmt"

	"github.com/screwyprof/interactor/v3"
)

type Hello struct{ Name string }

type Greeting struct{ Text string }

func main() {
	shout := interactor.UseCaseFunc[Hello, Greeting](func(_ context.Context, req Hello) (Greeting, error) {
		return Greeting{Text: "HELLO, " + req.Name + "!"}, nil
	})

	var d interactor.Dispatcher

	d.MustRegister(shout)

	greeting, err := d.Dispatch[Greeting](context.Background(), Hello{Name: "Gopher"})
	if err != nil {
		fmt.Println(err)

		return
	}

	fmt.Println(greeting.Text)

}
Output:
HELLO, Gopher!

func (UseCaseFunc[Req, Res]) Run

func (f UseCaseFunc[Req, Res]) Run(ctx context.Context, req Req) (Res, error)

Run calls f(ctx, req).

Directories

Path Synopsis
Package testdsl is a Given/When/Then DSL for testing your own use cases.
Package testdsl is a Given/When/Then DSL for testing your own use cases.

Jump to

Keyboard shortcuts

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