Golang的字符编码介绍

                  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 目录中完成安装。

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

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

 1 package main
 2 
 3 import (
 4     "bytes"
 5     "golang.org/x/text/encoding/simplifiedchinese"
 6     "golang.org/x/text/transform"
 7     "io/ioutil"
 8     "fmt"
 9 )
10 
11 func GbkToUtf8(s []byte) ([]byte, error) {
12     reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewDecoder())
13     d, e := ioutil.ReadAll(reader)
14     if e != nil {
15         return nil, e
16     }
17     return d, nil
18 }
19 
20 
21 func Utf8ToGbk(s []byte) ([]byte, error) {
22     reader := transform.NewReader(bytes.NewReader(s), simplifiedchinese.GBK.NewEncoder())
23     d, e := ioutil.ReadAll(reader)
24     if e != nil {
25         return nil, e
26     }
27     return d, nil
28 }
29 
30 func main() {
31     s := "尹正杰到此一游"
32     gbk, err := Utf8ToGbk([]byte(s))
33     if err != nil {
34         fmt.Println(err)
35     } else {
36         fmt.Println("以GBK的编码方式打开:",string(gbk))
37     }
38 
39     utf8, err := GbkToUtf8(gbk)
40     if err != nil {
41         fmt.Println(err)
42     } else {
43         fmt.Println("以UTF8的编码方式打开:",string(utf8))
44     }
45 }

  以上代码执行结果如下:

原文地址:https://www.cnblogs.com/yinzhengjie/p/7956689.html