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

 

posted @   两仪清风  阅读(6199)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示