You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
102 lines
2.1 KiB
102 lines
2.1 KiB
package evio
|
|
|
|
import "errors"
|
|
|
|
var ErrClosed = errors.New("evio was closed")
|
|
|
|
// Handler 事件处理器
|
|
type Handler interface {
|
|
// Handle 事件处理函数
|
|
Handle(any) error
|
|
}
|
|
|
|
type HandlerFunc func(any) error
|
|
|
|
func (h HandlerFunc) Handle(data any) error {
|
|
return h(data)
|
|
}
|
|
|
|
func Priority(priority int) SubscribeOption {
|
|
return func(h Handler) {
|
|
if x, ok := h.(interface{ SetPriority(int) }); ok {
|
|
x.SetPriority(priority)
|
|
}
|
|
}
|
|
}
|
|
|
|
func Once(once bool) SubscribeOption {
|
|
return func(h Handler) {
|
|
if x, ok := h.(interface{ SetOnce(bool) }); ok {
|
|
x.SetOnce(once)
|
|
}
|
|
}
|
|
}
|
|
|
|
// 订阅器初始化接口
|
|
type Initializer interface {
|
|
// Init 初始化订阅器
|
|
Init(Evio)
|
|
}
|
|
|
|
// Oncer 一次性订阅器接口,使订阅器只会被执行一次
|
|
type Oncer interface {
|
|
// Once 订阅器表示是否只执行一次
|
|
Once() bool
|
|
}
|
|
|
|
// Prioritizer 优先级接口,订阅器执行顺序,
|
|
type Prioritizer interface {
|
|
// Priority 返回优先级,值越小越先执行
|
|
// 如果订阅器为实现该接口,其优先级为 0
|
|
Priority() int
|
|
}
|
|
|
|
type Matcher interface {
|
|
Match(topic string) bool
|
|
}
|
|
|
|
type SubscribeOption func(Handler)
|
|
|
|
// Unsubscriber 订阅取消函数
|
|
type Unsubscriber func() bool
|
|
|
|
// Evio 时间管理接口
|
|
type Evio interface {
|
|
// Call 调用事件,是 Publish 的同步实现
|
|
//
|
|
// * "foo.bar" 具体事件
|
|
// * "*.bar" 后缀相同
|
|
// * "foo.*" 前缀相同
|
|
// * *.bar.* 中间包含
|
|
//
|
|
// 注意:前缀匹配必须包含符号 `.`。
|
|
Call(topic string, data any)
|
|
// Publish 发布事件,参数 topic 是模式。
|
|
Publish(topic string, data any) error
|
|
// Subscribe 订阅主题
|
|
Subscribe(topic string, handler Handler, opts ...SubscribeOption) (Unsubscriber, error)
|
|
// Listen 监听主题值
|
|
Listen(topic string) (stop func(), data <-chan any, err error)
|
|
// Start 启动事件服务
|
|
Start() error
|
|
// Stop 停止
|
|
Stop() error
|
|
}
|
|
|
|
type Error struct {
|
|
err error
|
|
topic string
|
|
data any
|
|
}
|
|
|
|
func (e *Error) Error() string {
|
|
return e.err.Error()
|
|
}
|
|
|
|
func (e *Error) Topic() string {
|
|
return e.topic
|
|
}
|
|
|
|
func (e *Error) Data() any {
|
|
return e.data
|
|
}
|
|
|