How to insert multiple tags into head tag

I’ve played around a big with net/html library and I’ve been able to modify each “src” attribute of each “img” tag to point to a different image. However, I’m a bit stumped here because I’m trying to do something a bit more complex. I need to insert some HTML into a pre-existing head tag. What I need to insert loks like this:

<![CDATA[\n<script type=\"text/javascript\">\nvar continentCode=\"EU\";\nvar doComplianceCheck=true;\n</script>\n<script src=\"/another.js\"></script>\n<script src=\"path/to/some.js\"></script>]]>

Is there a simple way to slap that into the head tag?
Thanks in advance for any assistance.
_Ramy

The simplest way is to use Javascript to add new code to innerHTML.

Not that simple but sort of “Go innerHTML” is to render both to buffer and then combine them into a new page. Pseudocode

var tpl *template.Template
var hdrbuf bytes.Buffer
var pagebuf bytes.Buffer

func main() {
	insert := `<div>injected header</div>`
	page := `<body><!-- PLACEHOLDER --></body>`

	tpl.ExecuteTemplate(&pagebuf, page, nil)
	tpl.ExecuteTemplate(&insert, page, nil)
	combined_buf := add_hdr2page()
	fmt.Println(combined_buf)

	// test
	fmt.Println(string(new_page))

}

// add header to every page
func add_hdr2page() []byte {
	placeholder := []byte(`<!-- PLACEHOLDER -->`)
	combined_buf := bytes.ReplaceAll(pagebuf.Bytes(), placeholder, hdrbuf.Bytes())
	return combined_buf
}

I’m getting a little lost in this code. Could you explain what the various variables are? Also I’m a bit unclear on how ExecuteTemplate works exactly. How do you specify which part of the pagebuf you want to insert your html into? I need to append to whatever is already in the HEAD tag.

There is three parts:

  1. page (main page)
  2. placeholder (where to insert)
  3. inject (what to insert)

You normally send the entire rendered template to the “http.ResponseWriter” (your website)

tpl.ExecuteTemplate(w, page, nil)

OR keep it in memory (buffer) until you write the html to the client direct as there is no need for re-rendering the combined html.

w.Write(combined_buf)

But as I said before there are other ways to do this simpler using Javascript OR inject by passing a parameter to the template.

{{.}}

ah ok i see what you mean now. The problem is that the HTML that I want to inject into is NOT a template. It’s an HTML page that’s coming from a webserver. So there isn’t anything in that HTML that says “insert here” or anything like you would have in a template. I just need to append my snippet to the HEAD tag as it comes to me from the webserver.

If it is a HTML page you can read it as HTML and insert as HTML IMO…

package main

import (
	"bytes"
	"fmt"
)

var hdrbuf bytes.Buffer
var pagebuf bytes.Buffer

func main() {
	//get snippet
	snippet := `<![CDATA[\n<script type=\"text/javascript\">\nvar continentCode=\"EU\";\nvar doComplianceCheck=true;\n</script>\n<script src=\"/another.js\"></script>\n<script src=\"path/to/some.js\"></script>]]>`
	pageHTML := `<head><!-- SNIPPET_HERE --></head>`

	// replace the INJECT_HERE "placeholder" with the snippet
	placeholder := []byte(`<!-- SNIPPET_HERE -->`)
	combined_page := bytes.ReplaceAll([]byte(pageHTML), placeholder, []byte(snippet))

	fmt.Println(string(combined_page))
	// Expected output: <body><div>injected header></div></body>
}


OR you can test with using <iframe> or <embed> depending on your need.

I ended up using goQuery as follows:


		bytes, err := io.ReadAll(resp.Body)
		if err != nil {
			fmt.Printf("Error generating HTML: %v\n", err)
			return
		}
		doc, err := goquery.NewDocumentFromReader(strings.NewReader(string(bytes)))
		if err != nil {
			fmt.Printf("Error generating HTML: %v\n", err)
			return
		}

		doc.Find("head").AppendHtml("<script type=\"text/javascript\">\nvar continentCode=\"EU\";\nvar doComplianceCheck=true;\n</script>\n<script src=\"/privacyservice.js\"></script>\n<script src=\"/path/to/some.js\"></script>")

		// Print the modified HTML
		modifiedHtml, err := doc.Html()
		if err != nil {
			fmt.Printf("Error generating HTML: %v\n", err)
			return
		}

		w.Header().Reset(resp.Header)
		w.Header().Del("Content-Type")

		w.WriteHeader(resp.StatusCode)
		fmt.Fprint(w, modifiedHtml)