Neurohazard
暮雲煙月,皓首窮經;森羅萬象,如是我聞。

Golang 遇到 unexpected EOF 的一个临时解决方案

wpadmin~August 28, 2019 /Software Engineering

Golang 遇到 unexpected EOF 的一个临时解决方案

解决

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    fmt.Println("Hello, playground")
    var buffer []byte
    buffer = make([]byte, 512)
    // 多次请求 字节数组缓冲可以复用

    client := &http.Client{}
    targetURL := "http://wp.blkstone.me"

    request, _ := http.NewRequest(http.MethodGet, targetURL, nil)
    request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0")

    response, _ := client.Do(request)

    body, err := ioutil.ReadAll(response.Body)

    if err != nil {
        // 如果 ioutil.ReadAll(response.Body) 发生错误
        // err 为 unexpected EOF
        fmt.Println(err)
        response, _ := client.Do(request)
        response.Body.Read(buffer)
        body = buffer
    }

    fmt.Print("HTTP Resposne:")
    fmt.Println(string(body))
}

Leave a Reply

Your email address will not be published. Required fields are marked *