import "code.google.com/p/go.text/encoding"
encoding包定义了字符编码的接口,例如Shift JIS和Windows 1252,可以将这些编码格式转换为utf-8。
要将一个io.Reader的字节数据从某种编码(e)转换为utf-8:rInUTF8 := transform.NewReader(r, e.NewDecoder())
将utf-8编码的数据转换为某种编码(e):
wInUTF8 := transform.NewWriter(w, e.NewEncoder())
两种情况下,都需要导入"code.google.com/p/go.text/transform"。
编码格式的具体实现在其他包里提供。
例如code.google.com/p/go.text/encoding/charmap和code.google.com/p/go.text/encoding/japanese。
const ASCIISub = '\x1a'
ASCIISub是ASCII替换字符,由该网页推荐:http://unicode.org/reports/tr36/#Text_Comparison
var ErrInvalidUTF8 = errors.New("encoding: invalid UTF-8")
ErrInvalidUTF8表示转换器遇到了非法的utf-8编码。
var UTF8Validator transform.Transformer = utf8Validator{}
UTF8Validator是一个空转换器,它会在遇到的非法utf-8编码的第一个字节时就返回ErrInvalidUTF8。
type Encoding interface { // NewDecoder返回一个将某种编码转换为utf-8编码的转换器。 // 当转换的编码并非期望的编码时,并不会导致错误。 // 输入中每一个不能被转换的编码都会在输出中被替换为替换码'\uFFFD'。 NewDecoder() transform.Transformer // NewEncoder返回一个将utf-8编码转换为期望编码的转换器。 // 当转换的编码是不合法的utf-8编码时,并不会导致错误。 // 每一个非法utf-8编码都会在被替换为转换器指定的替换码,如'\x1a'或者"\xff\xfd"。 // 如果要在遇到非法编码时尽快返回,使用transform.Chain函数和UTF8Validator预处理数据。 NewEncoder() transform.Transformer }
Encoding接口代表代表一个可以和utf-8互相转换的字符集。
var Nop Encoding = nop{}
Nop是无操作的Encoding接口。它的两个方法返回的转换器都会将提供给它的数据原封不动的返回,也不会替换非法的utf-8序列。
var Replacement Encoding = replacement{}
Replacement是仅替换操作的Encoding接口。它的Decoder方法返回的转换器只会生成单个'\uFFFD'替换码值;它的Encoder方法返回的转换器会将提供给它的数据原封不动的返回,但会将非法的utf-8序列替换为'\uFFFD'。