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
+19.3k Golang : Example for DSA(Digital Signature Algorithm) package functions
+14.3k Golang : Overwrite previous output with count down timer
+4.3k Javascript : Detect when console is activated and do something about it
+16.9k Golang : How to tell if a file is compressed either gzip or zip ?
+25.7k Mac/Linux and Golang : Fix bind: address already in use error
+11.1k Android Studio : Create custom icons for your application example
+17.5k Golang : How to make a file read only and set it to writable again?
+19.1k Golang : Fix cannot download, $GOPATH not set error
+10.2k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+13.9k Golang : Check if a file exist or not
+7.7k Golang : What fmt.Println() can do and println() cannot do
+12.4k Golang : Remove or trim extra comma from CSV