TCP长连接用json通信服务端怎么确定服务?

51300520 · 2018-06-06 18:32:09 · 1254 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2018-06-06 18:32:09 的主题,其中的信息可能已经有所发展或是发生改变。

初次做长连接服务,遇到点小问题,以前都是http的,以url确定服务

举个例子说得清楚点 比如有2个服务,一个登录一个聊天,客户端传过来对应的json是

登录: {"type":"login","username":"abc","password":"123456"} 聊天: {"type":"chat","from":"张三","to":"李四","content":"李四你好"} json的type字段就表明了请求什么服务

对于golang通常我们要把这俩json解析为对应的结构体:

type Login struct{

Type string
Username string
Password string

}

type Chat struct{

Type string
From string
To string
Content string

}

问题就是我在刚收到json字符串还不知道type是什么情况下怎么确定把该json解析到相应的结构体?我该 json.Unmarshal(json,?)

矛盾在于 这个type要解析过后才知道,然而解析的时候还不知道type我不知道该解析为哪个结构体 或者说我一开始的设计思路就是错的?


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1254 次点击  
加入收藏 微博
5 回复  |  直到 2018-06-07 14:53:47
254244460
254244460 · #1 · 7年之前

一种思路是嵌套,里面的data延迟解析,另一种思路是解析两次,或者还有还有一种方式是解析到map[string] interface{}里 type Msg struct{ Type string Data json.rawmessage }

51300520
51300520 · #2 · 7年之前
254244460254244460 #1 回复

一种思路是嵌套,里面的data延迟解析,另一种思路是解析两次,或者还有还有一种方式是解析到map[string] interface{}里 type Msg struct{ Type string Data json.rawmessage }

请问嵌套延迟解析是怎么回事?

marlonche
marlonche · #3 · 7年之前
{
  "type": "login",
  "data": {
    "username": "abc",
    "password": "123456"
  }
}

{
  "type": "chat",
  "data": {
    "from": "张三",
    "to": "李四",
    "content": "李四你好"
  }
}

type Msg struct {
        Type     string
        Data     json.RawMessage //具体数据的json,内容根据Type区别后继续unmarshal到Login或Chat
        Login   *Login
        Chat    *Chat
}
marlonche
marlonche · #4 · 7年之前

也可以把 Login和Chat合并到一个interface类型的变量,然后根据Type来区分; 如果Login和Chat能满足同一套接口,都不用区分具体类型

human
human · #5 · 7年之前

把登录和聊天的所有字段都写到一个结构体中,收到发送过来的json后直接unmarshal解析。然后根据type判断类型,如果是登录就解析username和password;如果是聊天就解析from、to、content。

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传