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

  • 相关阅读:
    an optimal solution to the problem
    sql_action
    rgb转灰度 RGB To Gray php Adobe RGB (1998) [gamma=2.20]
    MTUTCP/IP协议栈linux kernelTCP丢包重传UDP高性能AI ip数据报 tcp数据报
    Metaheuristic
    a computercentered view of information systems to a databasecentered view
    算法 图像识别 搜索
    var wi = 0; wi < arr.length; wi++
    模拟信号 数字信号
    locations in main memory to be referenced by descriptive names rather than by numeric addresses
  • 原文地址:https://www.cnblogs.com/lyqf365/p/3739533.html
Copyright © 2011-2022 走看看