meta.go 851 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package codec
  2. import (
  3. "fmt"
  4. "reflect"
  5. "sync"
  6. )
  7. type MsgPack struct {
  8. Router any
  9. DataPtr any
  10. Err error
  11. }
  12. var modelMap = make(map[any]reflect.Type)
  13. var modelMapLock sync.RWMutex
  14. func RegisterMessage(router any, datePtr any) {
  15. modelMapLock.Lock()
  16. defer modelMapLock.Unlock()
  17. if _, ok := modelMap[router]; ok {
  18. fmt.Println(fmt.Sprintf("codec: repeat registration. router:%s ", router))
  19. return
  20. }
  21. if t, ok := datePtr.(reflect.Type); ok {
  22. modelMap[router] = t.Elem()
  23. } else {
  24. t := reflect.TypeOf(datePtr)
  25. if t.Kind() != reflect.Ptr {
  26. panic(fmt.Errorf("codec: cannot use non-ptr message struct `%s`", t))
  27. }
  28. modelMap[router] = t.Elem()
  29. }
  30. }
  31. func GetMessage(router any) any {
  32. modelMapLock.RLock()
  33. defer modelMapLock.RUnlock()
  34. if ptr, ok := modelMap[router]; ok {
  35. return reflect.New(ptr).Interface()
  36. }
  37. return nil
  38. }