Golang的字符编码介绍

/ go / 没有评论 / 1755浏览

Golang的字符编码介绍

Go里面内建仅支持UTF8字符串编码,因此如果你用fmt.Printf之类的函数无法将GBK,GB2312等编码随意转换打印。在 Golang 中转换 UTF-8 与 GBK 编码的文本,可以使用 Go 官方的 golang.org/x/text 包实现,这个包可以通过下面的命令安装:“go get golang.org/x/text”。

如果访问 golang.org 站点存在困难,也可以使用下面的命令通过 github 下载 text 包的代码,下载完成后,再手工将其移动至 $GOROOT 目录中完成安装。

[root@yinzhengjie github.com]# git clone --depth 1 https://github.com/golang/text.git
[root@yinzhengjie github.com]# ll
总用量 24
drwxr-xr-x+  3 root root 4096 12月  5 16:14 gorilla
drwxr-xr-x+  3 root root 4096 11月 22 09:43 Go-SQL-Driver
drwxr-xr-x+ 20 root root 4096 12月  7 12:30 text
[root@yinzhengjie github.com]# pwd
/yinzhengjie/golang/path/src/github.com
[root@yinzhengjie github.com]# mkdir -p golang.org/x/
[root@yinzhengjie github.com]# cp text -R  golang.org/x/
[root@yinzhengjie github.com]# go env | grep GOROOT
GOROOT="/yinzhengjie/golang/local"
[root@yinzhengjie github.com]# cp -r /yinzhengjie/golang/path/src/github.com/golang.org /yinzhengjie/golang/local/src/
[root@yinzhengjie github.com]#

 接下来我们看一个典型的案例:

package main

import (
    "bytes"
    "golang.org/x/text/encoding/simplifiedchinese"
    "golang.org/x/text/transform"
    "io/ioutil"
    "fmt"
)

func GbkToUtf8(s []byte) ([]byte, error) {
    reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewDecoder())
    d, e := ioutil.ReadAll(reader)
    if e != nil {
        return nil, e
    }
    return d, nil
}


func Utf8ToGbk(s []byte) ([]byte, error) {
    reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewEncoder())
    d, e := ioutil.ReadAll(reader)
    if e != nil {
        return nil, e
    }
    return d, nil
}

func main() {
    s := "尹正杰到此一游"
    gbk, err := Utf8ToGbk([]byte(s))
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("以GBK的编码方式打开:",string(gbk))
    }

    utf8, err := GbkToUtf8(gbk)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("以UTF8的编码方式打开:",string(utf8))
    }
}