利用mahonia库来转换编码
GitHub上的项目地址mahonia
直接安装:go get github.com/axgle/mahonia
src:="要转换的字符串,假设原本是GBK编码,要转换为utf-8"
srcDecoder := mahonia.NewDecoder("gbk")
desDecoder := mahonia.NewDecoder("utf-8")
resStr:= srcDecoder.ConvertString(src)_,
resBytes, _ := desDecoder .Translate([]byte(resStr), true)
src = string(resBytes)
上面的代码可以封装成函数,直接获得转码后的结果
封装成函数
func UseNewEncoder(src string,oldEncoder string,newEncoder string) string{
srcDecoder := mahonia.NewDecoder(oldEncoder)
desDecoder := mahonia.NewDecoder(newEncoder)
resStr:= srcDecoder.ConvertString(src)
_, resBytes, _ := desDecoder .Translate([]byte(resStr), true)
return string(resBytes)}
调用函数
UseNewEncoder("要转编码的字符串","gbk","utf-8")
原文地址:https://www.jianshu.com/p/9ceae300c78e