micro

package
v1.0.0-beta.1 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package micro is the transport-independent part of Dygo microservices: message and event handlers declared by providers, a client to call other services, and an in-process transport for tests. Brokers live in their own modules (github.com/dygoframework/dygo/micro/nats).

A provider with a Patterns method declares handlers, the way a controller declares routes:

func (c *UsersHandlers) Patterns(r micro.Router) {
	r = r.Use(dygo.Guards(dygo.Ref[*ServiceTokenGuard]()))
	r.Message("users.get", micro.Handle(c.Get))        // request/response, like @MessagePattern
	r.Event("orders.created", micro.HandleEvent(c.OnOrder)) // fire and forget, like @EventPattern
}

func (c *UsersHandlers) Get(ctx context.Context, in GetUser) (*User, error)

Payloads are JSON. Guards, interceptors, pipes and filters work as on HTTP routes, with ExecutionContext.Kind() == dygo.KindRPC and the message in ExecutionContext.RPC(). Errors travel back to the caller in the errs error body ({"statusCode": 404, "message": ...}), so an *errs.HTTPError returned by a handler comes out of Send as the same *errs.HTTPError.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoHandler = errors.New("micro: no handler for the pattern")

ErrNoHandler is returned when no service handles a message pattern.

Functions

func DecodeReply

func DecodeReply(reply []byte, out any) error

DecodeReply is the client side of EncodeReply: it decodes the data into out (a pointer, or nil to ignore it) or returns the remote error as an *errs.HTTPError.

func EncodeReply

func EncodeReply(out any, err error) []byte

EncodeReply encodes a handler result or error. Errors are mapped with errs.ToBody: an *errs.HTTPError keeps its status and message, anything else becomes a 500 without details. dygo.ErrFiltered encodes as an empty reply.

func Send

func Send[Out any](ctx context.Context, c *Client, pattern string, in any) (Out, error)

Send is Client.Send with a typed result.

func WithHeader

func WithHeader(ctx context.Context, key, value string) context.Context

WithHeader returns ctx with a header that the client sends with every message made with it.

Types

type Client

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

Client calls other services. Provide one per broker connection and inject it.

func NewClient

func NewClient(t ClientTransport, opts ...ClientOption) *Client

NewClient returns a client that sends through t.

func (*Client) Emit

func (c *Client) Emit(ctx context.Context, pattern string, in any) error

Emit publishes an event; it does not wait for handlers.

func (*Client) Send

func (c *Client) Send(ctx context.Context, pattern string, in, out any) error

Send calls the handler of pattern with in and decodes its result into out (a pointer, or nil). A remote error is returned as an *errs.HTTPError.

type ClientOption

type ClientOption func(*Client)

ClientOption configures NewClient.

func Before

func Before(fn func(ctx context.Context, m *Message) error) ClientOption

Before adds a hook that runs before every message is sent, to set headers or refuse the call.

func Timeout

func Timeout(d time.Duration) ClientOption

Timeout bounds requests whose context has no deadline (5 seconds by default).

type ClientTransport

type ClientTransport interface {
	// Request sends m and waits for the encoded reply.
	Request(ctx context.Context, m *Message) (reply []byte, err error)
	// Publish sends m without waiting.
	Publish(ctx context.Context, m *Message) error
}

ClientTransport sends messages to a broker. Transports such as micro/nats implement it.

type Endpoint

type Endpoint struct {
	Pattern string
	// Event is true for event handlers.
	Event bool
	// contains filtered or unexported fields
}

Endpoint is one registered handler with its pipeline.

func (*Endpoint) Info

func (e *Endpoint) Info() dygo.RouteInfo

Info describes the handler.

func (*Endpoint) Serve

func (e *Endpoint) Serve(ctx context.Context, m *Message) (reply []byte, err error)

Serve handles one message: it decodes the payload, runs the pipeline and encodes the reply (EncodeReply) for message handlers. A reply is always returned for message handlers, holding the error when there is one; err is the error itself, for logging, or dygo.ErrFiltered when a filter caught it.

type Handler

type Handler interface {
	// contains filtered or unexported methods
}

Handler is a typed handler made by Handle or HandleEvent.

func Handle

func Handle[In, Out any](fn func(ctx context.Context, in In) (Out, error)) Handler

Handle makes a request/response handler. The payload is decoded into In and the result encoded as JSON.

func HandleEvent

func HandleEvent[In any](fn func(ctx context.Context, in In) error) Handler

HandleEvent makes an event handler.

type Handlers

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

Handlers is the set of handlers a transport serves.

func Collect

func Collect(a *dygo.App, o ServerOptions) (*Handlers, error)

Collect finds every Patterns provider of a and builds the pipelines of their handlers. Transports call it from Listen. Duplicate message patterns and enhancer problems are returned together.

func (*Handlers) All

func (hs *Handlers) All() []*Endpoint

All lists every endpoint, messages first, each sorted by pattern.

func (*Handlers) EventPatterns

func (hs *Handlers) EventPatterns() []string

EventPatterns lists the event patterns, sorted.

func (*Handlers) Events

func (hs *Handlers) Events(pattern string) []*Endpoint

Events returns the handlers of an event pattern.

func (*Handlers) Message

func (hs *Handlers) Message(pattern string) (*Endpoint, bool)

Message returns the handler of a message pattern.

func (*Handlers) MessagePatterns

func (hs *Handlers) MessagePatterns() []string

MessagePatterns lists the message patterns, sorted.

type Local

type Local struct {

	// OnError, when set, gets errors of event handlers and failed requests.
	OnError func(ctx context.Context, m *Message, err error)
	// contains filtered or unexported fields
}

Local is a transport inside the process: a dygo.Transport for the handlers and a ClientTransport that calls them. Tests use it to run a service's handlers without a broker; messages are copied as if they went over the wire.

local := micro.NewLocal(micro.ServerOptions{})
app.ConnectMicroservice(local)
client := micro.NewClient(local)

func NewLocal

func NewLocal(o ServerOptions) *Local

NewLocal returns an in-process transport.

func (*Local) Close

func (l *Local) Close(ctx context.Context) error

Close implements dygo.Transport.

func (*Local) Listen

func (l *Local) Listen(_ context.Context, a *dygo.App) error

Listen implements dygo.Transport.

func (*Local) Publish

func (l *Local) Publish(ctx context.Context, m *Message) error

Publish implements ClientTransport. Event handlers run before it returns.

func (*Local) Request

func (l *Local) Request(ctx context.Context, m *Message) ([]byte, error)

Request implements ClientTransport.

type Message

type Message struct {
	// Pattern is the subject or topic.
	Pattern string
	// Header carries metadata such as a trace or correlation ID.
	Header map[string]string
	// Data is the JSON payload.
	Data []byte
	// Raw is the transport's own message (for example *nats.Msg), or nil.
	Raw any
}

Message is one message on the wire.

func MessageFrom

func MessageFrom(ctx context.Context) (*Message, bool)

MessageFrom returns the message being handled. Handlers get a context that carries it.

type Patterns

type Patterns interface {
	Patterns(r Router)
}

Patterns is a provider that declares message and event handlers.

type Router

type Router interface {
	// Use returns a router whose handlers all get opts (enhancers and
	// metadata), like Router.Use on a controller.
	Use(opts ...dygo.RouteOption) Router
	// Message registers a request/response handler. One handler per pattern.
	Message(pattern string, h Handler, opts ...dygo.RouteOption)
	// Event registers an event handler. A pattern may have several.
	Event(pattern string, h Handler, opts ...dygo.RouteOption)
}

Router registers the handlers of one provider.

type ServerOptions

type ServerOptions struct {
	// Global enhancers for every handler of the transport, such as
	// dygo.Guards(...).
	Global []dygo.RouteOption
	// InheritAppConfig also runs the app's global enhancers (WithGlobal*
	// options and App* groups).
	InheritAppConfig bool
	// Filter keeps only the patterns it returns true for, when a process
	// runs several transports. Nil keeps all.
	Filter func(pattern string) bool
}

ServerOptions configures Collect.

Directories

Path Synopsis
nats module

Jump to

Keyboard shortcuts

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