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
+14.5k Golang : Parsing or breaking down URL
+34k Golang : Call a function after some delay(time.Sleep and Tick)
+11.3k Golang : Calculate Relative Strength Index(RSI) example
+25.1k Golang : Create PDF file from HTML file
+48k Golang : Convert int to byte array([]byte)
+6.8k Golang : Reverse by word
+12.3k Golang : List running EC2 instances and descriptions
+36.7k Golang : Validate IP address
+4.4k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+4.5k Java : Generate multiplication table example
+14.6k Golang : How to get URL port?
+29.5k Golang : JQuery AJAX post data to server and send data back to client example