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
+9.3k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+6.4k Golang : Handling image beyond OpenCV video capture boundary
+16.8k Golang : Set up source IP address before making HTTP request
+10.2k Golang : Random Rune generator
+25.2k Golang : Get current file path of a file or executable
+8.9k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+4.6k MariaDB/MySQL : How to get version information
+25.9k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+23.8k Golang : Fix type interface{} has no field or no methods and type assertions example
+7.8k Golang : Ways to recover memory during run time.
+5.5k Python : Print unicode escape characters and string
+7.1k Golang : Use modern ciphers only in secure connection