请问在这一串代码中resp.body为什么会从第1025个字符开始读取
但是bodyReader就没事呢,感觉resp.body也没被处理呀
``````
package fetcher
import (
"bufio"
"fmt"
"golang.org/x/net/html/charset"
"golang.org/x/text/encoding"
"golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
"io/ioutil"
"log"
"net/http"
)
const url = "http://www.zhenai.com/zhenghun"
func Fetch(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil,
fmt.Errorf("wrong status code: %d", resp.StatusCode)
}
bodyReader := bufio.NewReader(resp.Body)
e := determinEncoding(bodyReader)
utf8Reader := transform.NewReader(resp.Body, e.NewDecoder()) // !!!!!问题出在这里
return ioutil.ReadAll(utf8Reader)
}
func determinEncoding(
r *bufio.Reader) encoding.Encoding {
bytes, err := r.Peek(1024)
if err != nil {
log.Printf("Fetcher error: %v", err)
return unicode.UTF8
}
e, _, _ := charset.DetermineEncoding(bytes, "")
return e
}
``````
有疑问加站长微信联系(非本文作者)