receiver.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. Name string //类名
  14. IsRawArg bool // 数据是否需要序列化
  15. }
  16. func RegisterHandler(components ...interface{}) map[string]*Handler {
  17. methods := make(map[string]*Handler)
  18. for _, component := range components {
  19. rt := reflect.TypeOf(component)
  20. rv := reflect.ValueOf(component)
  21. typeName := reflect.Indirect(rv).Type().Name()
  22. if typeName == "" {
  23. continue
  24. }
  25. if !util.IsExported(typeName) {
  26. continue
  27. }
  28. for m := 0; m < rt.NumMethod(); m++ {
  29. method := rt.Method(m)
  30. mt := method.Type
  31. mn := method.Name
  32. if isHandlerMethod(method) {
  33. raw := false
  34. if mt.In(2) == typeOfBytes {
  35. raw = true
  36. }
  37. mn = strings.ToLower(mn)
  38. methods[mn] = &Handler{
  39. Receiver: rv,
  40. Method: method,
  41. Type: mt.In(2),
  42. Name: strings.ToLower(typeName),
  43. IsRawArg: raw,
  44. }
  45. }
  46. }
  47. }
  48. for name, handler := range methods {
  49. router := fmt.Sprintf("%s.%s", handler.Name, name)
  50. codec.RegisterMessage(router, handler.Type)
  51. }
  52. return methods
  53. }