receiver.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package service
  2. import (
  3. "fmt"
  4. "git.bvbej.com/bvbej/base-golang/pkg/websocket/codec"
  5. "git.bvbej.com/bvbej/base-golang/pkg/websocket/util"
  6. "reflect"
  7. "strings"
  8. )
  9. type Handler struct {
  10. Receiver reflect.Value // 值
  11. Method reflect.Method // 方法
  12. Type reflect.Type // 类型
  13. IsRawArg bool // 数据是否需要序列化
  14. }
  15. func RegisterHandler(components ...interface{}) map[string]*Handler {
  16. methods := make(map[string]*Handler)
  17. for _, component := range components {
  18. rt := reflect.TypeOf(component)
  19. rv := reflect.ValueOf(component)
  20. typeName := reflect.Indirect(rv).Type().Name()
  21. if typeName == "" {
  22. continue
  23. }
  24. if !util.IsExported(typeName) {
  25. continue
  26. }
  27. for m := 0; m < rt.NumMethod(); m++ {
  28. method := rt.Method(m)
  29. mt := method.Type
  30. mn := method.Name
  31. if isHandlerMethod(method) {
  32. raw := false
  33. if mt.In(2) == typeOfBytes {
  34. raw = true
  35. }
  36. router := fmt.Sprintf("%s.%s", strings.ToLower(typeName), strings.ToLower(mn))
  37. methods[router] = &Handler{
  38. Receiver: rv,
  39. Method: method,
  40. Type: mt.In(2),
  41. IsRawArg: raw,
  42. }
  43. }
  44. }
  45. }
  46. for router, handler := range methods {
  47. codec.RegisterMessage(router, handler.Type)
  48. }
  49. return methods
  50. }