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
+35.2k Golang : Convert(cast) int64 to string
+5.6k Golang : Skip or discard items of non-interest when iterating example
+15.4k Golang : Set up source IP address before making HTTP request
+6.3k Golang : Getting Echo framework StartAutoTLS to work
+13.1k Golang : Reset buffer example
+5.1k Golang : Get missing location after unmarshal binary and gob decode time.
+5.2k Javascript : Generate random key with specific length
+18k Mac OSX : Homebrew and Golang
+16.4k Golang : How to log each HTTP request to your web server?
+18.3k Golang : Archive directory with tar and gzip
+26.5k Get file path of temporary file in Go