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
+4.5k Golang : Reclaim memory occupied by make() example
+18.4k Golang : Check if os.Stdin input data is piped or from terminal
+4.6k Golang : Display advertisement images or strings on random order
+48.9k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+9.6k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+13.3k Golang : On enumeration
+8.5k Golang : Get all countries currencies code in JSON format
+13k Golang : Convert IP version 6 address to integer or decimal number
+4.3k Gogland : Datasource explorer
+9.6k Golang : Create matrix with Gonum Matrix package example
+31.7k Delete a directory in Go
+23.3k Golang : GORM read from database example