Get golang variable value in html script tag

I have to get the heroku version from golang code and pass this version to the
<script src="mysecript.js?t=version">
so that I can implement d cache busting to our site.

html/template will let you insert go data into generated html.

Can you please provide me sample for this
Thanks

The author, @joncalhoun, also participates on this forum.

Hi @nathankerr I have gone through the link but i am unable to get the Go lang variable value in the html page(script tag)

let me clear : I want value from GoLang to HTML page not HTML to GoLang

like in PHP we can get the value of PHP variable in the html page

<script src="script.js?<?php echo $var;?>"></script>

Perhaps I am misunderstanding something.

Could you give some example Go and HTML to help explain what you want?

This is our main.go file, where I am getting version from environment

appVersion:=fmt.Sprintf(os.Getenv(“version”))


public/Index.html file
like this
<link href="assets/css/css-new/gocustom.css?v="+appVersion rel="stylesheet"/>

I need to use GoLang appVersion variable in the index.html page.

This example will read in index.html and replace {{.AppVersion}} with the value set in data.

main.go

package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"os"
)

func main() {
	log.SetFlags(log.Lshortfile)

	appVersion := fmt.Sprintf(os.Getenv("version"))

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		tmpl, err := template.ParseFiles("index.html")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}

		data := struct {
			AppVersion string
		}{
			AppVersion: appVersion,
		}

		err = tmpl.Execute(w, data)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})

	fmt.Println("http://127.0.0.1:3000")
	log.Fatalln(http.ListenAndServe("127.0.0.1:3000", nil))
}

index.html

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>

<p>Version: {{.AppVersion}}</p>

</body>
</html>

Hi ,

Can we use this .AppVersion variable inside script tag like this.

<link href="assets/style.css?v="+{{.AppVersion}} rel="stylesheet"/>

Like this:

<link href="assets/style.css?v={{.AppVersion}}" rel="stylesheet"/>

What @nathankerr is saying is correct. The coolest part about the html/template package is that it is aware of where you inserting variables and does encoding for you. Eg if you insert a variable inside an href like in a link tag it will actually URL encode that value for you by default.

I mention this because I find it awesome but also because it might throw you off coming from PHP and you may try to encode it yourself.

1 Like

Hi @nathankerr and @joncalhoun when I implement this in Angular Js and trying to load js in index.html page like this.

<script src="assets/js/enscroll-0.6.2.min.j?v={{.AppVersion}}"></script>

I get this error.

Error: [$parse:syntax] Syntax Error: Token ‘.’ not a primary expression at column 1 of the expression [.AppVersion] starting at [.AppVersion].
http://errors.angularjs.org/1.3.13/$parse/syntax?p0=.&p1=not%20a%20primary%20expression&p2=1&p3=.AppVersion&p4=.AppVersion
at angular.js:63
at Parser.throwError (angular.js:12011)
at Parser.primary (angular.js:11989)
at Parser.unary (angular.js:12271)
at Parser.multiplicative (angular.js:12254)
at Parser.additive (angular.js:12245)
at Parser.relational (angular.js:12236)
at Parser.equality (angular.js:12227)
at Parser.logicalAND (angular.js:12218)
at Parser.logicalOR (angular.js:12209)

Can you please help me out, why I am getting this error??

and also I am not able to do this in the HTML tag also

Version: {{.AppVersion}}

What do you mean by “implement this in Angular Js”?

The error you mentioned is a JavaScript error, but the fact that it sees the text “.AppVersion” suggests that your go code is never processing the template and replacing that piece with an actual value.

My best guess is that you aren’t actually executing the template that is being rendered, but without seeing more of your code it is hard to suggest any sort of fix.

Hi @joncalhoun @nathankerr
I am not able to do anyting inside HandleFunc , means when i am doing fmt.Println(“hello”) , it is not executing . I guess this piece of code is not running on my system .
Can you please help me out what is the problem.
I am using angular js for the frontend and I am trying to access index.html page with the URL:http://localhost:8080/#/admin/dashboard

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		tmpl, err := template.ParseFiles("index.html")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}

		data := struct {
			AppVersion string
		}{
			AppVersion: appVersion,
		}

		err = tmpl.Execute(w, data)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})

My guess is that you are serving your frontend (angular js) with node and not Go. If this is the case, the handler is not running because nothing is accessing it.

Please describe your current architecture (e.g., frontend, backend, what serves what, what role does go play in this).

Hi @nathankerr I am serving Go as Backend and Angular js as frontend . when I parse the file “public/index.html” using
template.ParseFiles(“public/index.html”) , I am able to parse it and can see all the content in terminal console but when I was trying to access variable name as var1 in html page with angular js i got the angular js error.
After then I felt it that it can be “Golang and AngularJS template conflict” this error so I changed in the Golang code and usedDelims("<<", ">>") function to avoid conflict but still I am not getting any error but my variable still not be accessible . I see my index.html page with << var1 >> not value.

Here is my GoLang code
main.go

   import "html/template"
   import  "fmt"
        indexTmpl := template.New("public/index.html").Delims("<<", ">>")
    	tmpl, errp := indexTmpl.ParseFiles("public/index.html")

    	if errp != nil {fmt.Println("Error")
    		log.Fatal(errp)
    	}
    	if tmpl !=nil{
    		fmt.Println("No error")
    	}
    	fmt.Println(tmpl)
    	
    	varmap := map[string]interface{}{
    		"var1": "value",
    		"var2": 100,
    	}
    	tmpl.Execute(os.Stdout, varmap)

Index.html page

<h1> <<.var1>> </h1>

How is your Angular JS code served?

This is the needful sample code There are many Scripts in the index.html

Like this

<head>
<script src="lib/jquery/jquery.min.js?cb=<<.var1>>"></script>
<script src="lib/jquery/bootstrap.js"></script>
<script src="lib/angular/angular.js"></script>
<script src="assets/js/app.min.js"></script>
</head>

<body>
<h1> <<.var1>> </h1>
</body>

and many more…

Your angular app is not being served by go.

  1. angular runs in the browser
  2. the error in your previous comment is from angular
  3. go’s template processing happens on the server
  4. after the go template is processed, the template variables have been replaced
  5. a template variable still existed to create the error in 2.
  6. your angular code is not served by go
    q.e.d

Since your angular code is not served by go, you can’t use go to affect the code being served.