Our Go server will be using a couple of libraries — the Echo library ( an excellent web framework ) and the Gorilla Websocket library ( an very necessary library that is used in many projects). Take a look at the code to see how everything fits together. And since I am writing this at midnight, I am going to do a tour guide overview of the main things to take away.
Some things that I would to point out, in no particular order:
Websockets create a bidirectional channel with the server and is basically an upgraded AJAX request. Being such, the same security model is used for both AJAX and Websocket connections. This means that if the client is not on the same server (the server meaning same domain and port) as the backend, you will have to set up Cross Origin Resource Sharing (CORS) on the server.
Go is a statically typed language, the same as C#, which means that we have to find a way to turn the messages from the websocket connection into our custom types. Go provides a builtin way to do this via struct tags. The messages between the frontend and the server are only two fields, but if this were a more full-fledged project, you would use the struct tags to control which fields are passed back and forth. You can read more about how to use struct tags to effect the encoding of a custom types here.
gamesocketfunction is the main engine of the server. Because we are using CORS, we have to specify which hosts we allow to connect to the server. Since this is an example, we allow anything to connect. In production, you would obviously list your the hosts that are whitelisted. We wrap the main body of the function in a never-ending loop because the the websocket is bidirectional and not the usual request-response like in HTTP/AJAX.
You can see a working example of the whole project by going here. Hopefully, this sparks your imagination in as far as what you are capable of doing with Unity3d and the web. By embedding your game into a webpage, you can connect your game to a database, the blockchain, or even physical devices.