duanjiao6731
2016-03-08 15:09
浏览 57
已采纳

Go和UTF-8编码-转换是自动的吗?

I am making http requests using Go.

request, err := http.NewRequest("GET", url, nil)

This request, if successful, returns a response.

response, err := client.Do(request)

After receiving a response, I want to save the content.

content, err := ioutil.ReadAll(response.Body)
ioutil.WriteFile(destination, content, 0644)

I looked at the Headers of the responses.

response.Header.Get("Content-Type")

I saw the majority are already UTF-8 encoded, which is good. But there are some that have different encodings. I know Go has built in unicode support. Does that mean that if I write, for example, the content of a big-5 encoded page, it will be automatically converted to utf-8? Or do I need to manually decode using the big-5 encoding and re-encode using utf-8?

Basically, I want to ensure that everything that gets written is utf-8 encoded. What is the best way to achieve this?

Thanks!

图片转代码服务由CSDN问答提供 功能建议

我正在使用Go发出http请求。

 请求,  err:= http.NewRequest(“ GET”,url,nil)
   
 
 

此请求,如果成功,将返回响应。

 响应,错误:= client.Do(request)
   
 
 

收到响应后,我要保存内容。

 内容,错误:= ioutil.ReadAll(response.Body)
ioutil.WriteFile(destination,content,0644)
   
 
 

我查看了响应的标题。

  response.Header.Get(“ Content-Type”)
   
 
  

我看到大多数已经是UTF-8编码的,这很好。 但是有些编码却不同。 我知道Go内置了unicode支持。 这是否意味着,例如,如果我编写big-5编码页面的内容,它将自动转换为utf-8? 还是我需要使用big-5编码进行手动解码,然后使用utf-8进行重新编码?

基本上,我想确保写入的所有内容都经过utf-8编码。 最好的方法是什么?

谢谢!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongrouyuan5685 2016-03-08 15:32
    已采纳

    What ioutil.ReadAll reads will be written with ioutil.WriteFile without any conversions whatsoever.

    If you want to force UTF-8 encoded you will have to do the de-/encoding yourself, e.g. with the help of golang.org/x/text/encoding{,/charmap} and/or the unicode/utf{8,16} packages.

    Be prepared for all sorts of ugliness and a lot of pain.

    打赏 评论

相关推荐 更多相似问题