Write web page into memory and then to header

I am trying to fetch a website from page header (Javascript). I have successfully done this by loading from file into header.

// write file content to page
func get_content(w http.ResponseWriter, val string) {
	content, err := ioutil.ReadFile("./public/tmpl/" + val + ".html")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Fprint(w, string(content))
}

Using the above code can load from file and then fetch into innerHTML in Go template.

But now I want to populate the page BEFORE I send it to the client. Sort of save to memory and then to the header? This pseudo code does not work. What is the correct syntax for this? Is it possible?

func handler(w http.ResponseWriter, r *http.Request) {
    //fetch json into menu variable
	var menu map[string]interface{}
	if err := json.Unmarshal([]byte(jsondata), &menu); err != nil {
		panic(err)
	}
    // store in memory
	var page bytes.Buffer
	page.WriteString(tpl.ExecuteTemplate(w, "nav.html", menu),

    //write to header - accessible from the client
	fmt.Fprint(w, string(page))
}

const jsondata = `{
	"main": [{
		"menu_id": "1",
		"menu_txt": "Home"
	}, {
		"menu_id": "2",
		"menu_txt": "Prefs"
	}],
	"sub": [{
		"menu_id": "3",
		"menu_txt": "Test"
	}, {
		"menu_id": "4",
		"menu_txt": "Test2"
	}]
}
`

The template looks like this:

<html>
  <body>
    <ul>
      {{ range .main }}
      <li id="{{.menu_id}}">{{.menu_txt}}</li>
      {{ end }}
    </ul>
    <ul>
      {{ range .sub }}
      <li id="{{.menu_id}}">{{.menu_txt}}</li>
      {{ end }}
    </ul>
  </body>
</html>

The error I get is:

missing ‘,’ before newline in argument list

You’re missing a closing paren for page.WriteString.

Also, add commas at the and of the menu_txt lines inside jsondata

1 Like

Thank you for pointing out my mistakes
But I think I found an even simpler solution.

//fetch json into menu varible

//write into buffer
var buf bytes.Buffer
tpl.ExecuteTemplate(&buf, "nav.html", menu)

//write to header -> able to fetch for Javascript
fmt.Fprint(w, buf.String())

And then use Javascript fetch()

function get_nav() {
    fetch("http://127.0.0.1:9097/nav")
      .then((res) => res.text())
      .then((response) => {
        document.body.innerHTML = response;
      })
      .catch((error) => alert("Error:", error));
  }

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.