Skip to content

Instantly share code, notes, and snippets.

@robertotambunan
Last active June 13, 2020 09:13
Show Gist options
  • Select an option

  • Save robertotambunan/d522bcc668d152b8feb4722a09a8cca4 to your computer and use it in GitHub Desktop.

Select an option

Save robertotambunan/d522bcc668d152b8feb4722a09a8cca4 to your computer and use it in GitHub Desktop.

Revisions

  1. robertotambunan renamed this gist Jun 13, 2020. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions gistfile1.txt → Go Template - Parsing Template.txt
    Original file line number Diff line number Diff line change
    @@ -21,8 +21,8 @@ func main() {

    // handling template call
    func templateWorldHandler(w http.ResponseWriter, r *http.Request) {
    var data AllData
    data.Nations = getWorldCoronaData()
    var data AllData
    data.Nations = getWorldCoronaData()
    t := template.Must(template.ParseFiles("templates/index-world.html"))
    t.Execute(w, data)
    }
  2. robertotambunan created this gist Jun 13, 2020.
    48 changes: 48 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    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
    }