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
+6.9k Fix sudo yum hang problem with no output or error messages
+39.1k Golang : How to iterate over a []string(array)
+5.6k Golang : Detect words using using consecutive letters in a given string
+20.6k Nginx + FastCGI + Go Setup.
+18.8k Golang : How to make function callback or pass value from function as parameter?
+8.2k Golang : Reverse text lines or flip line order example
+30.1k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+14.4k Golang : On enumeration
+15.2k Golang : How to add color to string?
+10.1k Golang : Test a slice of integers for odd and even numbers
+15.6k Golang : rune literal not terminated error
+11.9k Golang : How to parse plain email text and process email header?