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
+17.6k Golang : How to make a file read only and set it to writable again?
+8.1k Golang : Check if integer is power of four example
+13.5k Golang : Activate web camera and broadcast out base64 encoded images
+8.4k Linux/Unix : fatal: the Postfix mail system is already running
+14k Golang : Fix image: unknown format error
+21.6k Golang : Convert string slice to struct and access with reflect example
+9.3k Golang : Play .WAV file from command line
+4.3k Golang : Valued expressions and functions example
+15.5k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy
+10k Golang : Get login name from environment and prompt for password
+12.7k Golang : http.Get example
+16.7k Golang : Get own process identifier