duanpang2751 2016-08-30 21:42
浏览 30
已采纳

ISO-8859-1编码网站中的Umlauts

My very simple code snippet:

import "net/http"
import "io"
import "os"

func main() {
  resp, err := http.Get("http://example.com")
  if err == nil {
    io.Copy(os.Stdout, resp.Body)
  }
}

When example.com is charset=iso-8859-1 encoded my output is faulty. Umlauts for example are not displayed correctly:

Hällo Wörld --> H?llo W?rld

Whats a good solution to display umlauts correctly??

  • 写回答

1条回答 默认 最新

  • dongxun1244 2016-08-31 00:01
    关注

    You can use the package golang.org/x/net/html/charset to determine the encoding of the website, and also create a reader that converts the content to UTF-8.

    Below is a working example:

    package main
    
    import (
        "io"
        "net/http"
        "os"
    
        "golang.org/x/net/html/charset"
    )
    
    func main() {
        resp, err := http.Get("http://example.com")
        if err != nil {
            os.Exit(1)
        }
    
        r, err := charset.NewReader(resp.Body, resp.Header.Get("Content-Type"))
        if err != nil {
            os.Exit(1)
        }
    
        io.Copy(os.Stdout, r)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部