<p>Hello all, I am trying to build a simple chat app to learn more about golang and am getting tripped up by json. When I try to decode I get no output and the "in" variable is empty. Here is my code so far for my client and server.</p>
<p>client:</p>
<pre><code>func main() {
out := Message{name: "Jacob", text: "hey whats up"}
conn, err := net.Dial("tcp", "127.0.0.1:6666")
if err != nil {
panic(err)
}
err := json.NewEncoder(conn).Encode(&out)
if err != nil {
panic(err)
}
}
</code></pre>
<p>server:</p>
<pre><code>func main() {
in := new(Message)
server, _ := net.Listen("tcp", "127.0.0.1:6666")
conn, _ := server.Accept()
err := json.NewDecoder(conn).Decode(&in)
if err != nil {
panic(err)
}
fmt.Println(in.name+":", in.text)
}
</code></pre>
<p>But when I run the two, my only output is ":". I know it has to be a dumb mistake, so any help or advice is appreciated!</p>
<hr/>**评论:**<br/><br/>Perelandric: <pre><p>Go can't encode/decode private fields.</p>
<hr/>
<p><em>EDIT:</em> Here's a working example with exported fields and field tags: <a href="https://play.golang.org/p/y-DmJ_iTPj" rel="nofollow">https://play.golang.org/p/y-DmJ_iTPj</a></p></pre>Eniac17: <pre><p>THANK YOU. Oh my I've been freaking out over this for two hours and forgot how go handled private fields. Oh the wonders of learning a new language </p></pre>Killing_Spark: <pre><p>So your example works because you defined message explicitly as a type with those two fields? </p>
<p>Sorry if this question is dumb I just started reading up on go :) </p></pre>Perelandric: <pre><p>No, the <code>Message</code> type was just left out of the question. It worked because I made the fields of <code>Message</code> public, meaning they can be accessed by code outside of the package in which it was defined.</p>
<p>Fields are made public by starting their name with a capital letter. So in the original code, it would have looked like this:</p>
<pre><code>type Message struct {
name string
text string
}
</code></pre>
<p>That defines a struct with two, private fields. Mine capitalizes those field names:</p>
<pre><code>type Message struct {
Name string
Text string
}
</code></pre>
<p>So now they're readable/writable by any code that gets a value of that type.</p>
<p>This is necessary because the <code>json</code> package <em>(or more accurately, the <code>reflect</code> package)</em> can only work with fields that it can access.</p></pre>Killing_Spark: <pre><p>Ah I see. Thanks for the thorough answer :) </p></pre>danredux: <pre><p>code looks good but i think maybe you're using too many indirections? maybe?</p>
<pre><code>in := new(Message) // in is now of type *Message
Decode(&in) // now you're passing **Message
</code></pre>
<p>same goes for your encode..</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传