Go实战--go中编码转换(The way to go)
2017-05-19 15:03
746 查看
生命不止,继续 go go go !!!
编码问题在每种语言中都会遇到,尤其对于中国的码农来说,更是常见的问题,因为我们的汉字有一点点特别。所以需要一些自己的编码,这就需要进行一些适当的转换。
例如,C++开发中,我们经常会用到wstring与string的互相转换。
所以,今天就介绍一下Golang中的编码转换,我们介绍一个库:mahonia
mahonia
Mahonia is a character-set conversion library implemented in Go. All data is compiled into the executable; it doesn’t need any external data files.
Mahonia is now deprecated. I recommend using the standard package at golang.org/x/text/encoding, possibly along with golang.org/x/net/charset
看到了作用了吧,但是,细心的朋友确实发现了上面英文描述的重点deprecated,已经被弃用了,但是我还是简单的介绍一下吧,共同学习。
下载源码
https://code.google.com/archive/p/mahonia/source/default/source
下载,解压,然后把mahonia文件夹放到GOPATH的src文件夹下即可(这里根据实际情况进行)。
读写文件
新建一个text.txt,键入内容“大宝剑”
写程序:
编码问题在每种语言中都会遇到,尤其对于中国的码农来说,更是常见的问题,因为我们的汉字有一点点特别。所以需要一些自己的编码,这就需要进行一些适当的转换。
例如,C++开发中,我们经常会用到wstring与string的互相转换。
所以,今天就介绍一下Golang中的编码转换,我们介绍一个库:mahonia
mahonia
Mahonia is a character-set conversion library implemented in Go. All data is compiled into the executable; it doesn’t need any external data files.
Mahonia is now deprecated. I recommend using the standard package at golang.org/x/text/encoding, possibly along with golang.org/x/net/charset
看到了作用了吧,但是,细心的朋友确实发现了上面英文描述的重点deprecated,已经被弃用了,但是我还是简单的介绍一下吧,共同学习。
下载源码
https://code.google.com/archive/p/mahonia/source/default/source
下载,解压,然后把mahonia文件夹放到GOPATH的src文件夹下即可(这里根据实际情况进行)。
读写文件
新建一个text.txt,键入内容“大宝剑”
写程序:
package main import ( "bufio" "fmt" "log" "mahonia" "os" "strings" "time" ) func main() { //生成日志文件 t := time.Now() filepath := "./log_" + strings.Replace(t.String()[:19], ":", "_", 3) + ".txt" file, err := os.OpenFile(filepath, os.O_CREATE, 0666) if err != nil { log.Fatal("failed!") } defer file.Close() wFile := bufio.NewWriter(file) wFile.WriteString(readfile()) wFile.Flush() } func readfile() string { f, err := os.Open("test.txt") if err != nil { return err.Error() } defer f.Close() buf := make([]byte, 1024) decoder := mahonia.NewDecoder("gb18030") if decoder == nil { fmt.Println("编码不存在!") return "编码不存在!" } var str string = "" for { n, _ := f.Read(buf) if 0 == n { break } //解码为UTF-8 fmt.Println(string(buf[:n])) str += decoder.ConvertString(string(buf[:n])) fmt.Println(str) } return str }
相关文章推荐
- Go实战--go中使用libphonenumber(The way to go)
- Go实战--go中使用base64加密(The way to go)
- Go实战--实现一个简单聊天室chatroom(The way to go)
- Go实战--xml与json相互转换(The way to go)
- Go实战--golang生成uuid(The way to go)
- Go实战--go中函数递归(recursion)的使用(The way to go)
- Go实战--go语言操作sqlite数据库(The way to go)
- Go实战--go语言中执行shell脚本(The way to go)
- Go实战--go中使用cookie(The way to go)
- Go实战--go中使用rpc(The way to go)
- Go实战--通过net/smtp发送邮件(The way to go)
- Go实战--实现一个单向链表(The way to go)
- Go实战--go中使用hmac sha256(The way to go)
- Go实战--压缩zip和解压缩unzip的应用(The way to go)
- Go实战--实现一个自己的网络请求日志httplogger(The way to go)
- Go实战--实现一个并发时钟服务器(The way to go)
- Go实战--go中一些有用的代码片段(The way to go)
- Go实战--golang新手入门常见错误(The way to go)
- Go实战--go中使用google/protobuf(The way to go)
- Go实战--实现简单的restful api(The way to go)