代码如下:
~~~go
...
//站点是http://2019.ip138.com/ic.asp
defer resp.Body.Close()
//判断编码
reader := bufio.NewReader(resp.Body)
bytes, e := reader.Peek(1024)
if e != nil && e != io.EOF{
return ""
}
encodig, _, _ := charset.DetermineEncoding(bytes, "")
utf8Reader := transform.NewReader(resp.Body, encodig.NewDecoder())
//这里的body为空,之前大部分页面这样转码是正常的,不知道什么问题
body, err := ioutil.ReadAll(utf8Reader)
~~~
````
package main
import (
"fmt"
"io/ioutil"
"net/http"
"github.com/axgle/mahonia"
)
func main() {
resp, err := http.Get("http://2019.ip138.com/ic.asp")
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
out, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
}
srcCoder := mahonia.NewDecoder("gbk")
resultstr := string(out)
fmt.Println(resultstr)
result := srcCoder.ConvertString(resultstr)
fmt.Println(result)
}
````
#2