Last active
October 28, 2024 08:18
-
-
Save james2doyle/e2f05b5756e4ee46848a8d987405f152 to your computer and use it in GitHub Desktop.
Use HTTP to GET and parse XML in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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