I encoded bytes to utf-8 using below function
func convrtToUTF8(origin []byte) []byte {
byteReader := bytes.NewReader(origin)
reader, _ := charset.NewReaderLabel("utf-8", byteReader)
strBytes, _ = ioutil.ReadAll(reader)
return strBytes
}
how can I convert strByte to origin?
Details,
origin bytes is from flatbuffers' builder.FinishedBytes() and I have to convert it to utf-8 bytes to use in websocket connection (Because Browser emits error like failed: Could not decode a text frame as UTF-8)
The code you provided seems to convert from UTF-8 to UTF-8:
NewReaderLabel returns a reader that converts from the specified charset to UTF-8. It uses Lookup to find the encoding that corresponds to label, and returns an error if Lookup returns nil. Source: GoDoc
You are not checking the returned errors, but decoding arbitrary binary as if it's UTF-8 encoded text will surely produce an error.
More importantly, you want to send binary data, don't encode it as UTF-8 like it's text. To send over a websocket, keep your data as binary:
Data frames (e.g., non-control frames) are identified by opcodes where the most significant bit of the opcode is 0. Currently defined opcodes for data frames include 0x1 (Text), 0x2 (Binary). Opcodes 0x3-0x7 are reserved for further non-control frames yet to be defined.
Source: RFC 6455
For example, if you're using github.com/gorilla/websocket
, you should read/write from the websocket using BinaryMessage
for the messageType
parameter.
The WebSocket protocol distinguishes between text and binary data messages. Text messages are interpreted as UTF-8 encoded text. The interpretation of binary messages is left to the application.
This package uses the TextMessage and BinaryMessage integer constants to identify the two data message types. The ReadMessage and NextReader methods return the type of the received message. The messageType argument to the WriteMessage and NextWriter methods specifies the type of a sent message.
Source: GoDoc