Skip to content

Instantly share code, notes, and snippets.

@timofeika
Forked from james2doyle/getXML.go
Created April 16, 2020 01:38
Show Gist options
  • Save timofeika/37cd02a4072e83cd50173a16474535ff to your computer and use it in GitHub Desktop.
Save timofeika/37cd02a4072e83cd50173a16474535ff to your computer and use it in GitHub Desktop.
Use HTTP to GET and parse XML in golang
// tweaked from: https://stackoverflow.com/a/42718113/1170664
func getXML(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return []byte{}, fmt.Errorf("GET error: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return []byte{}, fmt.Errorf("Status error: %v", resp.StatusCode)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte{}, fmt.Errorf("Read body: %v", err)
}
return data, nil
}
if xmlBytes, err := getXML("http://somehost.com/some.xml"); err != nil {
log.Printf("Failed to get XML: %v", err)
} else {
var result myXMLstruct
xml.Unmarshal(xmlBytes, &result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment