zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    深入剖析ASP.NET的编译原理之一:动态编译(Dynamical Compilation)
    ASP.NET Process Model之二:ASP.NET Http Runtime Pipeline Part I
    IIS Server Variables(IIS 服务器变量)
    .Net源码之Page类(二)
    博客改变生活
    目录、路径、虚拟路径
    Windows 7 Beta 1 7000
    《Visual Studio Hacks 》读书笔记 (十二)
    新建XML文件
    另一个分页函数
  • 原文地址:https://www.cnblogs.com/lyqf365/p/3739533.html
Copyright © 2011-2022 走看看