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
+9.1k Golang : Convert file content to Hex
+10.3k Golang : How to flush a channel before the end of program?
+7.9k Golang : Generate EAN barcode
+4.7k Swift : Get substring with rangeOfString() function example
+35k Golang : Display float in 2 decimal points and rounding up or down
+8.9k Golang : Find and replace data in all files recursively
+3.9k Unix/Linux : How to pipe/save output of a command to file?
+22k Find and replace a character in a string in Go
+10.7k Golang : Decompress zlib file example
+9.4k Golang : ISO8601 Duration Parser example
+7.9k Golang : How to use Gorilla webtoolkit context package properly
+12.6k Golang : Gin framework accept query string by post request example