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.1k Golang : Populate or initialize struct with values example
+5.9k Unix/Linux : How to test user agents blocked successfully ?
+9.3k Golang : Simple histogram example
+7.6k Android Studio : How to detect camera, activate and capture example
+9.3k Golang : How to capture return values from goroutines?
+17.1k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+28.7k Golang : Change a file last modified date and time
+5.9k Get website traffic ranking with Similar Web or Alexa
+6.2k Golang : Convert Chinese UTF8 characters to Pin Yin
+6.1k Fontello : How to load and use fonts?
+11.8k Golang : Display a text file line by line with line number example
+5.6k Golang *File points to a file or directory ?