Gorilla websockets' writejson() func gives string in message frame in brower

(Taalhach) #1

I am implementing websockets where i want to send an object of struct type after encoding it but when i used write json or nextWriter method from gorilla websocet toolkit for encoding it gives data in string is there any way i can send json to client so that he doesn’t need to parse data

code link:https://play.golang.org/p/3jb0ENTLi7Y

write json code snippet

for {
	for range ch {
		for _, con := range allConnection {
			c := OB{}
			c.Asks, c.Bids = GetPeparedVals()
			w, err := con.NextWriter(websocket.TextMessage)
			if err != nil {
				fmt.Println("encoding error")
			err = json.NewEncoder(w).Encode(&c)
			if err != nil {



(Johan Dahl) #2

But json is a string representation of an object. Then you can decode it and get a javascript object on the client side. Websockets can only send data in three types string, Blob (just a big blob of binary data) and ArrayBuffer which is an array of for examle ints. So to parse the data on your client all you have to do is:

mywebsocket.onmessage = function(event) {
  var msg = JSON.parse(event.data);

and now msq is a javascript object which you can use to access fields like msg.orderID, msg.Book[33].Title and so on

Or did I missunderstand you?

(Taalhach) #3

totally got it thanks man for helping me
God bless you