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。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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代理 了,记录一下