Golang 字符编码

需要添加的库

go get code.google.com/p/go.text/encoding
go get code.google.com/p/go.text/transform

两个转码函数

import (
    "bytes"
    "code.google.com/p/go.text/encoding/simplifiedchinese"
    "code.google.com/p/go.text/transform"
    "io/ioutil"
)

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

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


下面是测试代码:

func main() {
    log.SetFlags(log.LstdFlags | log.Lshortfile)
    resp, err := http.Get("http://data.earthquake.cn/datashare/globeEarthquake_csn.html")
    if err != nil {
        log.Fatal(err)
    }

    defer resp.Body.Close()
    input, err := ioutil.ReadAll(resp.Body)
    out := make([]byte, len(input))
    out = out[:]
    out, _ = Decode(input)
    ioutil.WriteFile("out.html", out, 0644)
    //func ReadFile(filename string) ([]byte, error)
    input, err = ioutil.ReadFile("out.html")
    out, _ = Encode(input)
    ioutil.WriteFile("out_gb.html", out, 0644)
}

还有以下是一些依赖iconv c库的开源字符集转换库:   

1.iconv-go,通过cgo封装了iconv库;
2.qiniu iconv,同样通过cgo封装iconv库;
3.go-charset,支持UTF-8转换为其他字符集(非iconv库),同时也封装了iconv,提供更多字符集的转换

这些在linux 上用用还好,到了windows 下要装mingw,而且又有32位和64位的区别,比较烦,所以个人不喜欢

另外还有一个Mahonia—a character-set conversion library for Go,但是这个库已经停止维护了。

如果没有特别的要求,个人还是建议使用 code.google.com/p/go.text/encoding

这个库要用hg来安装,记得先安装python 2.7 和Mercurial

原文地址:https://www.cnblogs.com/lyqf365/p/3739533.html