<p>Hello people,
I am trying to make game server on GO and stuck with messaging. I feel like i am digging in wrong direction... maybe someone can help me?
So, i have JS client and GO server. They should communicate through websockets. And here comes the question: Is there any best practices or pattern how to organize this communication? For example i will have 30 different messages with different data. Something like this:</p>
<pre><code>{
"command": "HELLO",
"username": "superuser",
"token": "ASdsdasdasd"
}
</code></pre>
<p>And another one:</p>
<pre><code>{
"command": "MOVE",
"x": 10,
"y": 10
}
</code></pre>
<p>On backend i have <em>websocket.Conn</em> connection and i am reading from it like <em>websocket.json.Receive(ws, &msg)</em>. But i can`t figure out how can i read completely different types of messages.</p>
<hr/>**评论:**<br/><br/>icholy: <pre><p>I'd do something like this: <a href="https://play.golang.org/p/E8hEK8YoPT" rel="nofollow">https://play.golang.org/p/E8hEK8YoPT</a></p></pre>nsd433: <pre><p>The two suggestions above are good. If you can't change the JSON, there's one more way: unpack twice. The first time you unpack into a struct type that just has one field, Command, and then switch on that and unpack again.</p>
<p>This works because the json.Unmarshal ignores fields which aren't present in both the JSON and the target type.</p></pre>materialdesigner: <pre><p>I'm glad someone else says this!</p>
<p>One of the most <em>powerful</em> aspects of the way golang does json deserialization is in how the same json string can be parsed into however many data types you need. Some people make monolithic parse types. No need! Use the pieces you need!</p></pre>rogeralsing: <pre><p>Use an envelope type that knows about all your messages. e.g. it can have a field for each known message type.</p>
<p>{
"hello" : {....}
"move" : {....}
}</p>
<p>This is how protobuf does it when you use the "oneof" directive.
you would then have to check for nil on each of those fields.</p>
<p>Maybe there is something more fancy for Go JSON, but thats the proto way at least.</p></pre>icholy: <pre><p>That's actually pretty clever ...</p></pre>tmornini: <pre><p>That is clever indeed!</p>
<p>Thanks!</p>
<p><a href="/u/ChangeTip" rel="nofollow">/u/ChangeTip</a> $1</p></pre>changetip: <pre><p><em>rogeralsing</em> received a tip for 2,201 bits ($1.00).</p>
<h2></h2>
<p><a href="https://www.reddit.com/r/changetip/wiki/tipping-on-reddit" rel="nofollow"><sup><sup>what</sup></sup> <sup><sup>is</sup></sup> <sup><sup>ChangeTip?</sup></sup></a></p></pre>tv64738: <pre><p>I wrote an article about that: <a href="http://eagain.net/articles/go-dynamic-json/" rel="nofollow">http://eagain.net/articles/go-dynamic-json/</a></p>
<p>Also likely useful: <a href="https://whispering-gophers.appspot.com/" rel="nofollow">https://whispering-gophers.appspot.com/</a></p></pre>