Tugrul Bayrak
Tugrul Bayrak

Reputation: 111

Reading bytes over TCP and encoding to ISO-8859-9 in Go

I am new to Golang. I am developing a service which reads bytes from remote address over TCP. The problem is that I can not change encoding of bytes I read. I want to convert the bytes I read to ISO-8859-9 string. Here is part of reading code.

 conn, err := net.Dial("tcp", constant.ConnectHost+":"+constant.ConnectPort)
 checkError(err)
 defer conn.Close()

 reader := bufio.NewReader(conn)
 textproc := textproto.NewReader(reader)

 bytes, err := textproc.R.ReadBytes(constant.EndTextDelimiter)
 checkError(err)
 msg := string(bytes[:])

Code works fine. But the encoding is different than I want. It is a problem for receiving service. Any suggestion?

Upvotes: 2

Views: 1480

Answers (1)

Tugrul Bayrak
Tugrul Bayrak

Reputation: 111

charmap.ISO8859_9.NewEncoder().Bytes() function wants UTF-8 format to encode. I was getting error when I try to encode my bytes. Because my incoming bytes are in 8859-9 format and I was trying to convert them directly. First I decode the bytes to UTF-8 format. I did my process, at the end I encoded this UTF-8 bytes to ISO8859-9 unicode using encoder. Here is the new code.

//main package
bytes, err := textproc.R.ReadBytes(constant.EndTextDelimiter)
checkError(err)
msg := encoder.DecodeISO8859_9ToUTF8(bytes)
//..........
// Process that string, create struct Then convert struct to json bytes
// Then encode that bytes
json := encoder.EncodeUTF8ToISO8859_9(bytes)

//encoder package
package encoder
import "golang.org/x/text/encoding/charmap"

func DecodeISO8859_9ToUTF8(bytes []byte) string {
    encoded, _ := charmap.ISO8859_9.NewDecoder().Bytes(bytes)
    return string(encoded[:])
}

func EncodeUTF8ToISO8859_9(bytes []byte) string {
    encoded, _ := charmap.ISO8859_9.NewEncoder().Bytes(bytes)
    return string(encoded[:])
}

Upvotes: 2

Related Questions