The best way to read data from Websockets

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]) } } 
+5
source share
1 answer

First, do not use websocket.Read and websocket.Write to read / write from / to websocket - it is better to use the convenient websocket.Message object and its corresponding functions websocket.Message.Receive() and websocket.Message.Send() . Both are used to send strings in UTF-8 encoding or in a sequence of bytes.

If you expect JSON objects to be sent to the socket, it is better to use websocket.JSON.Receive() instead of websocket.Message.Receive .

Use it as follows:

  ... type Person struct { Name string Emails []string } func ReceivePerson(ws *websocket.Conn) { var person Person err := websocket.JSON.Receive(ws, &person) if err != nil { log.Fatal(err) } ... 
+5
source

Source: https://habr.com/ru/post/1271548/


All Articles