登录
首页 >  Golang >  Go问答

使用 Go 读取 TCP 字节并将其编码为 ISO-8859-9

来源:stackoverflow

时间:2024-02-26 16:00:19 278浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《使用 Go 读取 TCP 字节并将其编码为 ISO-8859-9》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

我是 golang 新手。我正在开发一项通过 tcp 从远程地址读取字节的服务。问题是我无法更改我读取的字节编码。我想将读取的字节转换为 iso-8859-9 字符串。这是阅读代码的一部分。

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[:])

代码运行良好。但编码与我想要的不同。这是接收服务的问题。有什么建议吗?


解决方案


charmap.iso8859_9.newencoder().bytes()函数想要utf-8格式进行编码。当我尝试对字节进行编码时出现错误。因为我传入的字节是 8859-9 格式,我试图直接转换它们。首先,我将字节解码为 utf-8 格式。我完成了我的过程,最后我使用编码器将这个 utf-8 字节编码为 iso8859-9 unicode。这是新代码。

//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[:])
}

以上就是《使用 Go 读取 TCP 字节并将其编码为 ISO-8859-9》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>