golang在处理中文时默认的是utf-8编码,当某些情况下遇到GBK编码或需要GBK编码时,就会出现显示乱码的问题。
1. simplifiedchinese
golang官方有针对中文编码转换的包:/x/text/encoding/simplifiedchinese
import "/x/text/encoding/simplifiedchinese"
func ConvertStr2GBK(str string) string {//将utf-8编码的字符串转换为GBK编码ret, err := simplifiedchinese.GBK.NewEncoder().String(str)return ret //如果转换失败返回空字符串//如果是[]byte格式的字符串,可以使用Bytes方法b, err := simplifiedchinese.GBK.NewEncoder().Bytes([]byte(str))return string(b)}
func ConvertGBK2Str(gbkStr string) string {//将GBK编码的字符串转换为utf-8编码ret, err := simplifiedchinese.GBK.NewDecoder().String(gbkStr)return ret //如果转换失败返回空字符串//如果是[]byte格式的字符串,可以使用Bytes方法b, err := simplifiedchinese.GBK.NewDecoder().Bytes([]byte(gbkStr))return string(b)}
一般情况下,simplifiedchinese.GBK与simplifiedchinese.GB18030可以通用,区别在于字符集不同。
2. mahonia
还可以使用第三方的包:/axgle/mahonia
func Convert2GBK(str string) string {return mahonia.NewEncoder("gbk").ConvertString(title)}
3. 例子
zserge/webview在显示网页窗口时,其title字符串如果包含中文,则在不同平台上要求传递的编码格式不同。
MacOS上直接传递utf-8编码的字符串,windows则需要传递GBK编码的字符串。
import "/zserge/webview"import "/x/text/encoding/simplifiedchinese"title := "微信扫码登录"if strings.ToLower(runtime.GOOS) == "windows" {//如果不转换为GBK编码,则窗口标题显示乱码title, _ = simplifiedchinese.GBK.NewEncoder().String(title)}webview.Open(title, uri, 400, 600, true)