时间是个幻觉
在同步印象笔记的接口中报错,报错的基本信息大致如下:
golang An invalid XML character (Unicode: 0x8) was found
原因在于,文本中包含了unicode不可见字符。所以,目标很明确,将不可见字符过滤掉。
我使用了"unicode/utf8"来进行处理,因为我们的数据库默认字符也是utf-8的。看一下这个package的描述:
Package utf8 implements functions and constants to support text encoded in UTF-8. It includes functions to translate between runes and UTF-8 byte sequences. See https://en.wikipedia.org/wiki/UTF-8
应该支持的条件是UTF-8的文本,我感觉GBK的应该不支持。刚兴趣的可以留言告诉我。
我们看一下unicode对照表,我看到一篇格式比较端正的CSDN的文章,大家可以去看:ASCII码、Unicode编码对照表 —— ASCII控制字符 Unicode编码 字符编码的前世今生,我截个图吧:
这些都是不可见字符,都需要替换掉。
// 我手直接码的,可能有编辑错误,有问题大家自己动手改改
originStr := "等待处理的字符串"
// 将字符串转换为rune数组
srcRunes := []rune(originStr)
// 创建一个新的rune数组,用来存放过滤后的数据
dstRunes := make([]rune, 0, len(srcRunes))
// 过滤不可见字符,根据上面的表的0-32和127都是不可见的字符
for _, c := range srcRunes {
if c >= 0 && c <= 31 {
continue
}
if c == 127 {
continue
}
dstRunes = append(dstRunes, c)
}
result := string(dstRunes)
没有对代码进行压测,也不知道性能怎么样,但感觉来看,应能应该不怎么样吧。
没有当下
rune是什么类型呢,看一下它的定义:
// rune is an alias for int32 and is equivalent to int32 in all ways. It is
// used, by convention, to distinguish character values from integer values.
type rune = int32