Golang的字符編碼介紹
git
做者:尹正傑github
版權聲明:原創做品,謝絕轉載!不然將追究法律責任。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]#
接下來咱們看一個典型的案例:spa
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 }
以上代碼執行結果以下:code