Skip to content

Instantly share code, notes, and snippets.

@briandignan
Last active July 1, 2024 12:26
Show Gist options
  • Save briandignan/7974962 to your computer and use it in GitHub Desktop.
Save briandignan/7974962 to your computer and use it in GitHub Desktop.
Sending a nested Go struct as JSON over a WebSocket to JavaScript
<html>
<head>
<title>WebSocket tutorial</title>
<script type="text/JavaScript" src="printJSONFromWebSocket.js"></script>
</head>
<body>
</body>
</html>
ws = new WebSocket("ws://localhost:8000/ws/");
ws.onopen = function (event) {
console.log("WEB SOCKET OPENED");
}
ws.onmessage = function (event) {
var obj = JSON.parse(event.data)
document.write("<br>onmessage: " + JSON.stringify(obj, null, 4) + "</br>");
console.log(JSON.stringify(obj, null, 4))
}
ws.onclose = function (event) {
console.log("WEB SOCKET CLOSED");
}
function addNode(node) {
console.log("Adding new node: " + node)
}
{
"Channel": {
"AddNodes": [
"node1",
"node2"
]
}
}
{
"Channel": {
"RemoveNodes": [
"node1",
"node2"
]
}
}
{
"Channel": {
"AddEdges": [
{
"SourceNode": "node1",
"TargetNode": "node2",
"Name": "request piece"
},
{
"SourceNode": "node2",
"TargetNode": "node3",
"Name": "cancel piece"
}
]
}
}
{
"Channel": {
"RemoveEdges": [
{
"SourceNode": "node1",
"TargetNode": "node2",
"Name": "request piece"
},
{
"SourceNode": "node2",
"DestNode": "node3",
"Name": "cancel piece"
}
]
}
}
package main
import (
"fmt"
"net/http"
"os"
"code.google.com/p/go.net/websocket"
"encoding/json"
)
type ChannelUpdate struct {
Channel interface{}
}
type AddNewNodes struct {
AddNodes []string
}
func main() {
if len(os.Args) != 2 {
fmt.Println("Usage: wstelnet port")
os.Exit(0)
}
port := os.Args[1]
fmt.Println("Serving web on port", port)
service := ":" + port
http.Handle("/", http.FileServer(http.Dir(".")))
http.Handle("/ws/", websocket.Handler(ProcessSocket))
err := http.ListenAndServe(service, nil)
checkError(err)
}
func ProcessSocket(ws *websocket.Conn) {
fmt.Println("In ProcessSocket")
nodes := make([]string, 2)
nodes[0] = "node1"
nodes[1] = "node2"
addNodes := new(AddNewNodes)
addNodes.AddNodes = nodes
channelUpdate := new(ChannelUpdate)
channelUpdate.Channel = addNodes
updateJson, err := json.Marshal(channelUpdate)
msg := string(updateJson)
err = websocket.Message.Send(ws, msg)
checkError(err)
ws.Close()
return
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ", err.Error())
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment