在 Golang 中,可以使用第三方库 "golang.org/x/net/html/charset" 来获取文本的编码。具体的实现方式如下:

import (
    "golang.org/x/net/html/charset"
    "golang.org/x/text/encoding"
    "golang.org/x/text/transform"
    "io/ioutil"
    "net/http"
)

func getCharset(resp *http.Response) encoding.Encoding {
    contentType := resp.Header.Get("Content-Type")
    _, params, err := charset.ParseMediaType(contentType)
    if err != nil {
        return nil
    }
    charset, err := charset.Lookup(params["charset"])
    if err != nil {
        return nil
    }
    return charset
}

func getBody(resp *http.Response) ([]byte, error) {
    defer resp.Body.Close()
    charset := getCharset(resp)
    if charset == nil {
        return ioutil.ReadAll(resp.Body)
    }
    reader := transform.NewReader(resp.Body, charset.NewDecoder())
    return ioutil.ReadAll(reader)
}

以上代码中,getCharset 函数根据 HTTP 响应的 Content-Type 头部获取编码方式,如果无法获取则返回 nil。getBody 函数则使用获取到的编码方式来解码响应的内容,并返回解码后的字节数据

golang 获取文本是哪种编码

原文地址: https://www.cveoy.top/t/topic/g9qL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录