gotd: add fallback handlers

Cherry-picked from https://github.com/gotd/td/commit/3238f7e7d3623ecd3648e2124f962c4ea0d03134
This commit is contained in:
Vadim Tertilov
2025-12-03 14:48:35 +02:00
committed by Tulir Asokan
parent 8e7a7db85f
commit 097211cba1
2 changed files with 31 additions and 13 deletions
+16 -7
View File
@@ -2,15 +2,16 @@
{{ $pkg := $.Package }}
{{ template "header" $ }}
type handler = func(context.Context, Entities, UpdateClass) error
type Handler = func(context.Context, Entities, UpdateClass) error
type UpdateDispatcher struct {
handlers map[uint32]handler
handlers map[uint32]Handler
fallback Handler
}
func NewUpdateDispatcher() UpdateDispatcher {
return UpdateDispatcher{
handlers: map[uint32]handler{},
handlers: map[uint32]Handler{},
}
}
@@ -71,10 +72,13 @@ func (u UpdateDispatcher) dispatch(ctx context.Context, e Entities, update Updat
}
typeID := update.TypeID()
handler, ok := u.handlers[typeID]
if !ok {
return nil
}
return handler(ctx, e, update)
if ok {
return handler(ctx, e, update)
}
if u.fallback != nil {
return u.fallback(ctx, e, update)
}
return nil
}
{{- range $s := $.Structs }}{{ if eq $s.Interface "UpdateClass" }}
@@ -90,4 +94,9 @@ func (u UpdateDispatcher) On{{ $eventName }}(handler {{ $eventName }}Handler) {
}
{{- end }}{{ end }}
// OnFallback sets fallback handler.
func (u *UpdateDispatcher) OnFallback(handler Handler) {
u.fallback = handler
}
{{ end }}
+15 -6
View File
@@ -31,15 +31,16 @@ var (
_ = tdjson.Encoder{}
)
type handler = func(context.Context, Entities, UpdateClass) error
type Handler = func(context.Context, Entities, UpdateClass) error
type UpdateDispatcher struct {
handlers map[uint32]handler
handlers map[uint32]Handler
fallback Handler
}
func NewUpdateDispatcher() UpdateDispatcher {
return UpdateDispatcher{
handlers: map[uint32]handler{},
handlers: map[uint32]Handler{},
}
}
@@ -100,10 +101,13 @@ func (u UpdateDispatcher) dispatch(ctx context.Context, e Entities, update Updat
}
typeID := update.TypeID()
handler, ok := u.handlers[typeID]
if !ok {
return nil
if ok {
return handler(ctx, e, update)
}
return handler(ctx, e, update)
if u.fallback != nil {
return u.fallback(ctx, e, update)
}
return nil
}
// NewMessageHandler is a NewMessage event handler.
@@ -1605,3 +1609,8 @@ func (u UpdateDispatcher) OnStarGiftAuctionUserState(handler StarGiftAuctionUser
return handler(ctx, e, update.(*UpdateStarGiftAuctionUserState))
}
}
// OnFallback sets fallback handler.
func (u *UpdateDispatcher) OnFallback(handler Handler) {
u.fallback = handler
}