codec.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. package rocommon
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/golang/protobuf/proto"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "net/url"
  12. "reflect"
  13. "strconv"
  14. "strings"
  15. )
  16. type Codec interface {
  17. Marshal(msg interface{}) (interface{}, error) //todo...上下文Context
  18. Unmarshal(data interface{}, msg interface{}) error
  19. TypeOfName() string
  20. }
  21. var registerCodec Codec //后续有别的解析部分这边可以添加
  22. var httpCodec Codec
  23. func init() {
  24. //注册protobuf解析
  25. RegisterCodec(new(pbCodec))
  26. httpCodec = &httpJsonCodec{}
  27. //httpCodec = &httpFormCodec{}
  28. }
  29. func RegisterCodec(c Codec) {
  30. log.Println("RegisterCodec pbcodec")
  31. registerCodec = c
  32. }
  33. func GetCodec() Codec {
  34. return registerCodec
  35. }
  36. func GetHttpCodec(codecName string) Codec {
  37. if codecName == "" {
  38. return httpCodec
  39. }
  40. switch codecName {
  41. case "httpform":
  42. return &httpFormCodec{}
  43. case "httpjson":
  44. return &httpJsonCodec{}
  45. }
  46. return httpCodec
  47. }
  48. //pbCodec
  49. type pbCodec struct {
  50. }
  51. func (this *pbCodec) TypeOfName() string {
  52. return "protobuf"
  53. }
  54. func (this *pbCodec) Marshal(msg interface{}) (interface{}, error) {
  55. return proto.Marshal(msg.(proto.Message))
  56. }
  57. func (this *pbCodec) Unmarshal(data interface{}, msg interface{}) error {
  58. return proto.Unmarshal(data.([]byte), msg.(proto.Message))
  59. }
  60. //http json
  61. type httpJsonCodec struct {
  62. }
  63. func (this *httpJsonCodec) TypeOfName() string {
  64. return "httpjson"
  65. }
  66. func (this *httpJsonCodec) MimeType() string {
  67. return "application/json"
  68. }
  69. func (this *httpJsonCodec) Marshal(msg interface{}) (interface{}, error) {
  70. httpData, err := json.Marshal(msg)
  71. if err != nil {
  72. return nil, err
  73. }
  74. //log.Printf("httpData:%v", httpData)
  75. return bytes.NewReader(httpData), nil
  76. }
  77. func (this *httpJsonCodec) Unmarshal(data interface{}, msg interface{}) error {
  78. var reader io.Reader
  79. switch v := data.(type) {
  80. case *http.Request:
  81. reader = v.Body
  82. case io.Reader:
  83. reader = v
  84. }
  85. body, err := ioutil.ReadAll(reader)
  86. if err != nil {
  87. return err
  88. }
  89. log.Println("httpJsonCodec:", string(body))
  90. return json.Unmarshal(body, msg)
  91. }
  92. //httpForm
  93. const defaultMemory = 32 * 1024 * 1024
  94. type httpFormCodec struct {
  95. }
  96. func (this *httpFormCodec) TypeOfName() string {
  97. return "httpform"
  98. }
  99. func (this *httpFormCodec) MimeType() string {
  100. return "application/x-www-form-urlencoded"
  101. }
  102. func (this *httpFormCodec) Marshal(msg interface{}) (interface{}, error) {
  103. return strings.NewReader(this.form2UrlValues(msg).Encode()), nil
  104. }
  105. func (this *httpFormCodec) Unmarshal(data interface{}, msg interface{}) error {
  106. //todo...
  107. /*
  108. var reader io.Reader
  109. switch v := data.(type) {
  110. case *http.Request:
  111. reader = v.Body
  112. case io.Reader:
  113. reader = v
  114. }
  115. body,err := ioutil.ReadAll(reader)
  116. if err != nil {
  117. return err
  118. }
  119. type aast struct{
  120. Ret int
  121. Msg string
  122. }
  123. var aa aast
  124. json.Unmarshal(body,&aa)
  125. log.Println("body11:", string(body), aa)
  126. */
  127. //log.Println("type:", reflect.TypeOf(data))
  128. //reader, err := gzip.NewReader(data.(io.Reader))
  129. if msg != nil {
  130. body, err := ioutil.ReadAll(data.(io.Reader))
  131. if err != nil {
  132. return err
  133. }
  134. //log.Println("body11:", string(body))
  135. msgValue := reflect.ValueOf(msg)
  136. if msgValue.Kind() == reflect.Ptr {
  137. msgValue = msgValue.Elem()
  138. }
  139. msgValue.Field(0).SetString(string(body))
  140. }
  141. //msg = this.value2String(string(body))
  142. //
  143. //resp := data.(*http.Request)
  144. //err = resp.ParseForm()
  145. //if err != nil {
  146. // return nil
  147. //}
  148. //log.Println("[httpFormCodec]body:", resp.Form)
  149. //resp.ParseMultipartForm(defaultMemory)
  150. return nil
  151. }
  152. func (this *httpFormCodec) form2UrlValues(obj interface{}) url.Values {
  153. objValue := reflect.Indirect(reflect.ValueOf(obj))
  154. objType := reflect.TypeOf(obj)
  155. formValues := url.Values{}
  156. for i := 0; i < objValue.NumField(); i++ {
  157. field := objType.Field(i)
  158. val := objValue.Field(i)
  159. //if field {
  160. formValues.Add(field.Name, this.value2String(val.Interface()))
  161. //}
  162. }
  163. return formValues
  164. }
  165. func (this *httpFormCodec) value2String(value interface{}) string {
  166. switch v := value.(type) {
  167. case string:
  168. return v
  169. case bool:
  170. return strconv.FormatBool(v)
  171. case int:
  172. return strconv.FormatInt(int64(v), 10)
  173. case int32:
  174. return strconv.FormatInt(int64(v), 10)
  175. case int64:
  176. return strconv.FormatInt(int64(v), 10)
  177. case float32:
  178. return strconv.FormatFloat(float64(v), 'f', -1, 32)
  179. case float64:
  180. return strconv.FormatFloat(v, 'f', -1, 64)
  181. default:
  182. panic("Unknown type to convert to string")
  183. }
  184. }
  185. /////////////////////
  186. type MessageInfo struct {
  187. Codec Codec
  188. Type reflect.Type
  189. ID int
  190. ConfirmMsgId int //需要确认的req消息,如果info是req则是ack的id,如果是ack则是req的id
  191. }
  192. var (
  193. messageByID = map[int]*MessageInfo{}
  194. messageByType = map[reflect.Type]*MessageInfo{}
  195. messageByName = map[string]*MessageInfo{}
  196. )
  197. func RegisterMessageInfo(info *MessageInfo) {
  198. //注册时统一为非指针类型
  199. if info.Type.Kind() == reflect.Ptr {
  200. info.Type = info.Type.Elem()
  201. }
  202. if info.ID == 0 {
  203. panic(fmt.Sprintf("message ID invalid:%v", info.Type.Name()))
  204. }
  205. if _, ok := messageByID[info.ID]; ok {
  206. panic(fmt.Sprintf("message has register id:%v", info.Type.Name()))
  207. } else {
  208. messageByID[info.ID] = info
  209. }
  210. if _, ok := messageByType[info.Type]; ok {
  211. panic(fmt.Sprintf("message has register type:%v", info.Type.Name()))
  212. } else {
  213. messageByType[info.Type] = info
  214. }
  215. if _, ok := messageByName[info.Type.Name()]; ok {
  216. panic(fmt.Sprintf("message has register name:%v", info.Type.Name()))
  217. } else {
  218. messageByName[info.Type.Name()] = info
  219. }
  220. //log.Printf("message register [id|type|name][%v%v|%v]\n", info.ID,info.Type,info.Type.Name())
  221. }
  222. func MessageInfoByID(id int) *MessageInfo {
  223. if data, ok := messageByID[id]; ok {
  224. return data
  225. }
  226. return nil
  227. }
  228. func MessageInfoByMsg(msg interface{}) *MessageInfo {
  229. msgType := reflect.TypeOf(msg)
  230. if msgType.Kind() == reflect.Ptr {
  231. if info, ok := messageByType[msgType.Elem()]; ok {
  232. return info
  233. }
  234. return nil
  235. } else {
  236. if info, ok := messageByType[msgType]; ok {
  237. return info
  238. }
  239. return nil
  240. }
  241. }
  242. func MessageInfoByName(name string) *MessageInfo {
  243. if info, ok := messageByName[name]; ok {
  244. return info
  245. }
  246. return nil
  247. }
  248. func MessageToString(msg interface{}) string {
  249. if msg == nil {
  250. return ""
  251. }
  252. if str, ok := msg.(interface{ String() string }); ok {
  253. return str.String()
  254. }
  255. return ""
  256. }