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
+5.9k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+9k Golang : Generate EAN barcode
+8.2k Golang : How to check variable or object type during runtime?
+15.6k Golang : Read a file line by line
+22.2k Golang : Convert Unix timestamp to UTC timestamp
+11.4k Golang : Concurrency and goroutine example
+13.1k Android Studio : Password input and reveal password example
+7.9k Golang : How To Use Panic and Recover
+22.5k Golang : simulate tail -f or read last line from log file example
+14.6k Golang : Submit web forms without browser by http.PostForm example
+7.5k Golang : Test if an input is an Armstrong number example
+9.7k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral