I'm currently learning Golang (and so far I love it). But unfortunately, I've been stuck for a couple hours and I don't seem to find any solution to my problem on Google.
So here's my problem. I have this piece of code (from a tutorial) :
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)
}
}
I know, my code is incomplete but that's because I deleted the parts that were not causing the problem to make it more readable on Stackoverflow.
So when I get the content of Location
and try to process the data with ioutil.ReadAll()
I get this error mentioning a pointer :
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
I really don't understand this error, no matter how much I look into it. I tried to pull the error from ioutil.ReadAll(resp.Body)
by doing _, e := ioutil.ReadAll(resp.Body)
and then printing e
, but doing that throws another error...
I read somewhere that it can be because the body returned to me has errors, but it's working fine in the tutorial.
Hopefully you guys will have a solution for me. Thanks.
EDIT : Here are the structs I have defined :
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
}