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.4k Golang : Frobnicate or tweaking a string example
+12.1k Golang : Convert(cast) int to int64
+14.7k Golang : Generate universally unique identifier(UUID) example
+20.9k Golang : Read directory content with filepath.Walk()
+4.1k Golang : Display packages names during compilation
+4.9k Facebook : How to force facebook to scrape latest URL link data?
+3.5k Javascript : Detect when console is activated and do something about it
+8.4k Golang : Convert(cast) string to int64
+5.4k CodeIgniter : form input set_value cause " to become & quot
+38.1k Golang : UDP client server read write example
+18.2k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+7.3k Golang : Convert word to its plural form example