美文网首页
golang中处理关于http请求返回非utf8编码问题

golang中处理关于http请求返回非utf8编码问题

作者: EasyNetCN | 来源:发表于2023-02-16 14:38 被阅读0次

使用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)
    }

相关文章

网友评论

      本文标题:golang中处理关于http请求返回非utf8编码问题

      本文链接:https://www.haomeiwen.com/subject/seupkdtx.html