I am learning Go (Golang) and have the project in mind. The project will be a web application that draws data from a third-party website. At this point, I am trying to run a Go project to read web socket data so that I can parse it.
A third-party website is a JSON object data stream.
So far, I have been able to successfully listen to the website. However, I am confused about how best to deal with this. Namely, the reading method that I use in the Websocket library gets a piece of byte. It seems complicated to turn into JSON objects. Is there a better way to read websocket - collecting JSON objects?
goal
My goal is to listen to this publicly accessible network socket, get json objects that I can parse for my desire field, which will then be pulled into the view (dynamic update with data stream).
If not, how can I convert a piece of bytes back to a JSON object?
code
Here is my code:
package main import ( "golang.org/x/net/websocket" "fmt" "log" ) func main(){ origin := "http://localhost/" url := "wss://ws-feed.gdax.com" ws, err := websocket.Dial(url, "", origin) if err != nil { log.Fatal(err) } if _, err := ws.Write([]byte(`{"type":"subscribe", "product_ids":["LTC-USD"]}`)); err != nil { log.Fatal(err) } var msg = make([]byte, 512) var n int for 1>0{ if n, err = ws.Read(msg); err != nil { log.Fatal(err) } fmt.Printf("Received: %s.\n", msg[:n]) } }
source share