使用golang中的http.client,在把请求返回的内容插入到mysql时,会抛出异常”Incorrect string value“,查看返回内容编码,不是utf8编码,导致发生异常,可以参考下面例子进行处理:
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"time"
"unicode/utf8"
"golang.org/x/text/encoding/simplifiedchinese"
)
if utf8.Valid(body) {
wrapper.Body = string(body)
} else if bytes, err := simplifiedchinese.GB18030.NewDecoder().Bytes(body); err == nil {
wrapper.Body = string(bytes)
} else if bytes, err := simplifiedchinese.GBK.NewDecoder().Bytes(body); err == nil {
wrapper.Body = string(bytes)
} else if bytes, err := simplifiedchinese.HZGB2312.NewDecoder().Bytes(body); err == nil {
wrapper.Body = string(bytes)
} else {
wrapper.Body = string(body)
}
网友评论