hello!
I would like to use the json output of a GET request to create a sort of html table but I don’t know how to do that.
My code is the following:
package main
import (
"encoding/json"
"fmt"
"html/template"
"net/http"
"os"
"time"
)
var answer string
type AutoGenerated struct {
Latest Latest `json:"latest"`
Locations []Locations `json:"locations"`
}
type Latest struct {
Confirmed int `json:"confirmed"`
Deaths int `json:"deaths"`
Recovered int `json:"recovered"`
}
type Coordinates struct {
Latitude string `json:"latitude"`
Longitude string `json:"longitude"`
}
type Locations struct {
ID int `json:"id"`
Country string `json:"country"`
CountryCode string `json:"country_code"`
Province string `json:"province"`
LastUpdated time.Time `json:"last_updated"`
Coordinates Coordinates `json:"coordinates"`
Latest Latest `json:"latest"`
}
var baseUrl = "https://coronavirus-tracker-api.herokuapp.com/v2"
var latestUrl = "/locations"
func getJson(url string, target interface{}) error {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Println(err)
}
req.Header.Add("content-type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println(err)
//return err.Error()
}
defer res.Body.Close()
return json.NewDecoder(res.Body).Decode(target)
}
var dataPage = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<ul>
{{range .}}
<li>
<span>{{.Country}} </span>
</li>
{{end}}
</ul>
</body>
</html>`
func main() {
var locationsUrl = baseUrl + latestUrl
var data AutoGenerated
getJson(locationsUrl, &data)
fmt.Printf("%+v\n", data)
tmp, err := template.New("data").Parse(dataPage)
if err != nil {
panic(err)
}
tmp.Execute(os.Stdout, data)
}
The idea is to get something like this:
https://coronavirus-tracker-api.herokuapp.com/v2/locations
I’ve tried to use html/template to have alist of the country printed on the html in the stdout but I didn’t get anything
Thanks