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
+32.6k Golang : Proper way to set function argument default value
+16.1k Golang : Multi threading or run two processes or more example
+12.5k Golang : Tutorial on loading GOB and PEM files
+5.7k Golang : Muxing with Martini example
+11.7k Android Studio : Password input and reveal password example
+11.6k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+28.2k Golang : Get and Set User-Agent examples
+9.3k JavaScript/JQuery : Detect or intercept enter key pressed example
+19k Golang : Secure(TLS) connection between server and client
+7.9k Golang : Find the length of big.Int variable example
+18.9k Golang : Count number of digits from given integer value
+17.2k Golang : Send email with attachment