Golang : Convert(cast) []byte to io.Reader type
Problem :
Need to convert XML data from http.Get()
to io.Reader type for xml.NewDecoder()
function to work . How to do that ?
Solution :
Use strings.NewReader()
function to convert the []byte type to io.Reader type.
For example :
domainName := "socketloop.com"
resp, err := http.Get("http://data.alexa.com/data?cli=10&url=" + domainName)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer resp.Body.Close()
alexaData, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// convert []byte to type io.Reader with strings.NewReader()
decoder := xml.NewDecoder(strings.NewReader(string(alexaData)))
Reference :
https://www.socketloop.com/references/golang-encoding-xml-decoder-rawtoken-example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12k Golang : How to get a user home directory path?
+4.1k Golang : Display packages names during compilation
+16.1k Golang : delete and modify XML file content
+16.1k Golang : When to use init() function?
+10.5k Golang : Sort and reverse sort a slice of runes
+9k Golang : Get escape characters \u form from unicode characters
+12.7k Golang : convert rune to unicode hexadecimal value and back to rune character
+7.6k Golang : Gaussian blur on image and camera video feed examples
+4.8k Golang : Error handling methods
+28.6k Golang : How to get HTTP request header information?
+15k Golang : Get file permission
+31.3k Golang : Smarter Error Handling with strings.Contains()