Skip to content

Instantly share code, notes, and snippets.

@robertotambunan
Last active June 13, 2020 09:13
Show Gist options
  • Save robertotambunan/d522bcc668d152b8feb4722a09a8cca4 to your computer and use it in GitHub Desktop.
Save robertotambunan/d522bcc668d152b8feb4722a09a8cca4 to your computer and use it in GitHub Desktop.
Parsing Template
import (
"html/template"
"log"
"net/http"
"os"
)
type AllData struct {
Nations []AttributeNationData
}
func main() {
port := os.Getenv("PORT")
if port == "" {
log.Fatal("$PORT must be set")
}
http.HandleFunc("/world", templateWorldHandler)
log.Println("running in port :", port)
http.ListenAndServe(":"+port, nil)
}
// handling template call
func templateWorldHandler(w http.ResponseWriter, r *http.Request) {
var data AllData
data.Nations = getWorldCoronaData()
t := template.Must(template.ParseFiles("templates/index-world.html"))
t.Execute(w, data)
}
// fetch data
func getWorldCoronaData() (result []AttributeNationData) {
req, err := http.NewRequest("GET", dataURLNation, nil)
if err != nil {
log.Println("NewRequest: ", err)
return
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Do: ", err)
return
}
defer resp.Body.Close()
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
log.Println("NewDecoder", err)
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment