【发布时间】:2018-12-27 03:11:11
【问题描述】:
我目前正在学习 Golang(到目前为止我很喜欢它)。但不幸的是,我被困了几个小时,似乎在 Google 上找不到任何解决问题的方法。
所以这是我的问题。我有这段代码(来自教程):
func main() {
var s SitemapIndex
resp, _ := http.Get("https://www.washingtonpost.com/news-sitemaps/index.xml")
bytes, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
xml.Unmarshal(bytes, &s)
for _, Location := range s.Locations {
resp, _ := http.Get(Location)
ioutil.ReadAll(resp.Body)
}
}
我知道,我的代码不完整,但那是因为我删除了不会导致问题的部分,使其在 Stackoverflow 上更具可读性。
所以当我得到Location 的内容并尝试使用ioutil.ReadAll() 处理数据时,我收到这个错误提示:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x1210a69]
goroutine 1 [running]:
main.main()
/Users/tom/Developer/Go/src/news/index.go:23 +0x159
exit status 2
我真的不明白这个错误,不管我怎么看。我试图通过执行_, e := ioutil.ReadAll(resp.Body) 然后打印e 来从ioutil.ReadAll(resp.Body) 中提取错误,但是这样做会引发另一个 错误...
我在某处读到可能是因为返回给我的正文有错误,但在教程中它运行良好。
希望你们能给我一个解决方案。谢谢。
编辑:这是我定义的结构:
type SitemapIndex struct {
Locations []string `xml:"sitemap>loc"`
}
type News struct {
Titles []string `xml:"url>news>title"`
Keywords []string `xml:"url>news>keywords"`
Locations []string `xml:"url>loc"`
}
type NewsMap struct {
Keyword string
Location string
}
【问题讨论】:
-
可以复制 SitemapIndex 来查看吗?
-
谢谢,我刚刚编辑了帖子
-
你忽略了错误,这样没人能发现问题。而不是丢弃错误处理它们。像这样。 resp,er := http.Get("your address");if err!= nil { log.Fataln(err) }