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
+5.7k Get website traffic ranking with Similar Web or Alexa
+7.8k Javascript : How to check a browser's Do Not Track status?
+25.2k Golang : Convert uint value to string type
+17.8k Golang : Simple client server example
+21.9k Golang : Join arrays or slices example
+4.9k Golang : Calculate a pip value and distance to target profit example
+7.1k CloudFlare : Another way to get visitor's real IP address
+15.2k nginx: [emerg] unknown directive "ssl"
+5.1k Golang : Customize scanner.Scanner to treat dash as part of identifier
+9.3k Golang : Terminate-stay-resident or daemonize your program?
+4.9k Python : Convert(cast) bytes to string example