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
+24.4k Golang : How to write CSV data to file
+12.1k Golang : error parsing regexp: invalid or unsupported Perl syntax
+6.8k Golang Hello World Example
+23.1k Golang : Time slice or date sort and reverse sort example
+9.4k Golang : Select region of interest with mouse click and crop from image
+15.6k Golang : Get input from keyboard
+11.6k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+5.2k Golang : Detect face in uploaded photo like GPlus
+8.8k Golang : Check a web page existence with HEAD request example
+8.2k Golang : How to control fmt or log print format?
+7.3k Golang : Ackermann function example
+11k Golang : 2 dimensional array example