iconv: libiconv for go


iconv is a libiconv wrapper for go. libiconv Convert string to requested character encoding.
Document
See http://godoc.org/github.com/qiniu/iconv
Note: Open returns a conversion descriptor cd, cd contains a conversion state and can not be used in multiple threads simultaneously.
Install
go get github.com/qiniu/iconv
Example
Convert string
package main
import (
"fmt"
"github.com/qiniu/iconv"
)
func main() {
cd, err := iconv.Open("gbk", "utf-8")
if err != nil {
fmt.Println("iconv.Open failed!")
return
}
defer cd.Close()
gbk := cd.ConvString("你好,世界!")
fmt.Println(gbk)
}
Output to io.Writer
package main
import (
"fmt"
"github.com/qiniu/iconv"
)
func main() {
cd, err := iconv.Open("gbk", "utf-8")
if err != nil {
fmt.Println("iconv.Open failed!")
return
}
defer cd.Close()
output := ...
autoSync := false
bufSize := 0
w := iconv.NewWriter(cd, output, bufSize, autoSync)
fmt.Fprintln(w, "你好,世界!")
w.Sync()
}
Input from io.Reader
package main
import (
"fmt"
"io"
"os"
"github.com/qiniu/iconv"
)
func main() {
cd, err := iconv.Open("utf-8", "gbk")
if err != nil {
fmt.Println("iconv.Open failed!")
return
}
defer cd.Close()
input := ...
bufSize := 0
r := iconv.NewReader(cd, input, bufSize)
_, err = io.Copy(os.Stdout, r)
if err != nil {
fmt.Println("\nio.Copy failed:", err)
return
}
}