Last active
June 13, 2020 09:13
-
-
Save robertotambunan/d522bcc668d152b8feb4722a09a8cca4 to your computer and use it in GitHub Desktop.
Parsing Template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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