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
+11.8k Golang : Overwrite previous output with count down timer
+3.8k PHP : Hide PHP version information from curl
+18.9k Golang : How to get time zone and load different time zone?
+6.3k Golang : Handle Palindrome string with case sensitivity and unicode
+6.6k Golang : How to extract video or image files from html source code
+6.3k Golang : Add build version and other information in executables
+5.2k PHP : Shuffle to display different content or advertisement
+8.9k Swift : Convert (cast) String to Integer
+5k Mac/Linux/Windows : Get CPU information from command line
+31k Golang : How to split or chunking a file to smaller pieces?
+23.5k Golang : Force your program to run with root permissions
+6.5k Golang : Check if integer is power of four example