小编典典
import "code.google.com/p/go-charset/charset"
func NewWriter(charset string, w io.Writer) (io.WriteCloser, error)
NewWriter将新的WriteCloser文字返回给w。它将UTF-8文本的写入转换w为命名字符集中的文本的写入。所述Close冲洗任何残留的部分翻译的字符到所述输出是必要的。
我将按照说明进行操作:“ Close必须将所有剩余的部分翻译的字符刷新到输出。” 例如,
package main
import (
"bytes"
"code.google.com/p/go-charset/charset"
_ "code.google.com/p/go-charset/data"
"fmt"
"io/ioutil"
"strings"
)
func toISO88591(utf8 string) (string, error) {
buf := new(bytes.Buffer)
w, err := charset.NewWriter("latin1", buf)
if err != nil {
return "", err
}
fmt.Fprintf(w, utf8)
w.Close()
return buf.String(), nil
}
func fromISO88591(iso88591 string) (string, error) {
r, err := charset.NewReader("latin1", strings.NewReader(iso88591))
if err != nil {
return "", err
}
buf, err := ioutil.ReadAll(r)
if err != nil {
return "", err
}
return string(buf), nil
}
func main() {
utfi := "£5 for Peppé"
fmt.Printf("%q\n", utfi)
iso, err := toISO88591(utfi)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%q\n", iso)
utfo, err := fromISO88591(iso)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%q\n", utfo)
fmt.Println(utfi == utfo)
}
输出:
"£5 for Peppé"
"\xa35 for Pepp\xe9"
"£5 for Peppé"
true
2020-07-02