这是我尝试使用的一个教科书示例。
我得到了“坏”的结果,这意味着resp是零,虽然我不知道如何修复它。
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
resp, _ := http.Get("http://example.com/")
if resp != nil {
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
resp.Body.Close()
} else {
fmt.Println("BAD")
}
}
发布于 2019-10-24 16:45:34
我建议您先检查您的Internet设置,因为我无法重现此问题。
此外,Go中的错误处理是至关重要的,所以请将您的代码更改为下面的代码,看看在发出请求时是否会出现任何错误。
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
resp, err := http.Get("http://example.com/")
if err != nil {
log.Fatalln(err)
}
if resp != nil {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
fmt.Println(string(body))
resp.Body.Close()
} else {
fmt.Println("BAD")
}
}
https://stackoverflow.com/questions/58537044
复制相似问题