Evan Hessler Evan Hessler - 2 years ago 164
HTTP Question

Golang display static HTML template while waiting for data to load

I have a route set up which responds with a dynamic HTML template.

package main

import (

func index(w http.ResponseWriter, r *http.Request) {
showWwResult, _ := GetWw()
showHoursResult, _ := GetHours()

type Data struct {
ShowWwResult []IssueResult
ShowHoursResult Page

data := Data{showWwResult, showHoursResult}

var templates = template.Must(template.ParseFiles("templates/index.html", "templates/ww.html", "templates/hours.html"))
templates.ExecuteTemplate(w, "indexPage", data)

My problem is, it takes a very long time to gather the data and the page waits for this to return before rendering the HTML.

How can I get it to return something, anything, while I wait for GetWw() and GetHours() to finish? Is there any way to display the static part of my HTML template and then populate the page with ShowWwResult and ShowHoursResult when they're ready?

Answer Source

No, the best way is to serve the template then populate it using ajax calls to an endpoint that returns json with the data you want to use.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download