meta.go 907 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package codec
  2. import (
  3. "fmt"
  4. "reflect"
  5. "sync"
  6. )
  7. type MsgPack struct {
  8. Router interface{}
  9. DataPtr interface{}
  10. Err error
  11. }
  12. var modelMap = make(map[interface{}]reflect.Type)
  13. var modelMapLock sync.RWMutex
  14. func RegisterMessage(router interface{}, datePtr interface{}) {
  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 interface{}) interface{} {
  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. }