spark-server/internal/transport/tcp/command_router.go
2026-09-16 19:08:06 +08:00

37 lines
1.0 KiB
Go

package tcp
import (
"context"
"spark-server/internal/pkg/errs"
"spark-server/internal/transport/tcp/protocol"
"spark-server/internal/transport/tcp/session"
)
// CommandHandler runs in TaskPool for AUTH/SEND/SYNC and other business commands.
type CommandHandler func(ctx context.Context, conn *session.Conn, frame protocol.Frame) (*protocol.Frame, error)
// Router maps Frame.Command to a handler.
type Router struct {
handlers map[uint16]CommandHandler
}
// NewRouter creates an empty command table.
func NewRouter() *Router {
return &Router{handlers: make(map[uint16]CommandHandler)}
}
// Register binds a command to a TaskPool handler.
func (r *Router) Register(cmd uint16, h CommandHandler) {
r.handlers[cmd] = h
}
// Dispatch looks up and runs the handler. Unknown commands are invalid.
func (r *Router) Dispatch(ctx context.Context, conn *session.Conn, frame protocol.Frame) (*protocol.Frame, error) {
h, ok := r.handlers[frame.Command]
if !ok {
return nil, errs.ErrInvalidArgument
}
return h(ctx, conn, frame)
}