H
H
hitakiri2017-06-13 17:49:39
go
hitakiri, 2017-06-13 17:49:39

How to correctly pass json data through websocket in golang?

There is a string of json data written in sqlite as TEXT.
The data is transmitted via gorilla-websocket. As part of the structure.

type SourseText struct {
 	id  int         `json:"id"`
 	sText  string         `json:"stext, omitempty"`
}
....
sText := '{"channel":"buu","name":"john", "msg":"doe"}'
....
err = conn.WriteJSON(SourseText)

The problem is that the data is escaped during transmission:
"{"id":{"1"},{\"channel\":\"buu\",\"name\":\"john\", \"msg\":\"doe\"}}"

I did not find a way to convey without dancing with a tambourine. Please help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlyuk, 2017-06-13
@hitakiri

WriteJSON expects a structure as input, which it then marshals into JSON. Your JSON is already marshaled, so use the WriteMessage method. The first argument there is the type of the message, you need binary, the second is directly JSON in the form of an array of bytes. A string can be converted to an array of bytes like this: []byte(sText)

A
Alexander Aksentiev, 2017-06-13
@Sanasol

WriteJSON, as it were, hints, and you already give him ready-made JSON.
It turns out double JSON.
https://github.com/gorilla/websocket/blob/2d1e4548...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question