I am trying to convert data through api url into JSON data. As a whole it works, but when I want to get specific data set from JSON (here I am trying MyStruct which is a data set having name, duration, listners), so it comes with blank result. On the other side, same problem with html template which does not give any result when I call it through local host port. I have declared a global instance to call data set in template function (could also use in my get content function though) but having fail result. I am wondered why data variable in get_content having blank result?
// created structurs example
type MyStruct struct {
Name string
Duration string
and so on..
}
var data1 MyStruct
// function to retreive api data & convert into json.
func get_content() {
// json data
url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
url += "" // limit data for testing
res, err := http.Get(url)
if err != nil {
panic(err.Error())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err.Error())
}
var data MyStruct
err = json.Unmarshal(body, &data)
if err != nil {
panic(err.Error())
}
fmt.Printf("Results: %v
", data)
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
get_content()
})
http.HandleFunc("/", template1)
http.ListenAndServe(":8080", nil)
}
func template1(w http.ResponseWriter, r *http.Request) {
fp := path.Join("index.html")
tmpl, err := template.ParseFiles(fp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := tmpl.Execute(w, data1); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
on index file I have written names to call the data:
{{.Name}}
{{.Duration}}
{{.Listeners}}