base-golang/pkg/websocket/client/service/receiver.go

58 lines
1.2 KiB
Go
Raw Normal View History

2024-07-23 10:23:43 +08:00
package service
import (
"fmt"
2024-07-31 16:49:14 +08:00
"gitea.bvbej.com/bvbej/base-golang/pkg/websocket/codec"
"gitea.bvbej.com/bvbej/base-golang/pkg/websocket/util"
2024-07-23 10:23:43 +08:00
"reflect"
"strings"
)
type Handler struct {
Receiver reflect.Value // 值
Method reflect.Method // 方法
Type reflect.Type // 类型
IsRawArg bool // 数据是否需要序列化
}
func RegisterHandler(components ...any) map[string]*Handler {
methods := make(map[string]*Handler)
for _, component := range components {
rt := reflect.TypeOf(component)
rv := reflect.ValueOf(component)
typeName := reflect.Indirect(rv).Type().Name()
if typeName == "" {
continue
}
if !util.IsExported(typeName) {
continue
}
for m := 0; m < rt.NumMethod(); m++ {
method := rt.Method(m)
mt := method.Type
mn := method.Name
if isHandlerMethod(method) {
raw := false
if mt.In(2) == typeOfBytes {
raw = true
}
router := fmt.Sprintf("%s.%s", strings.ToLower(typeName), strings.ToLower(mn))
methods[router] = &Handler{
Receiver: rv,
Method: method,
Type: mt.In(2),
IsRawArg: raw,
}
}
}
}
for router, handler := range methods {
codec.RegisterMessage(router, handler.Type)
}
return methods
}