Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active October 28, 2024 08:18
Show Gist options
  • Save james2doyle/e2f05b5756e4ee46848a8d987405f152 to your computer and use it in GitHub Desktop.
Save james2doyle/e2f05b5756e4ee46848a8d987405f152 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