[Solved] Referencing os.Hostname() in Go Template

Hey everyone! I am dying and full on Q_Q with this exercise lol.

I have a Kubernetes demo for the folks at work. All that is working fine, but I thought “It would be cool to have the hostname show up on the web page.”

REST. IN. PEACE. lmao

I have never struggled with something so much. I have very little experience with front-end, so I apologize in advance for low quality code (a lot has been removed in the name of brevity):

The server:

type HostInfo struct {
    Name string
}

h, _ := os.Hostname()

host := HostInfo{}
host.Name = h

err = tpl.ExecuteTemplate(w, "layout", host)

The template:

{{ .host.Name }}

I have tried:

{{ . }}
{{ .Name }}
{{ .HostInfo.Name }}
{{ .HostInfo }}
{{ printf "%s" [all of the above combinations] }}

The templates work, I can change pages and I can {{ printf "%s" "Hello, Go!" }} <br> and it works as expected.

I just can’t access the variable. Any ideas on what to try next?

Thank you for your time! Appreciate any and all assistance!

Try something like:

	tpl := template.Must(template.New("t1").Parse("hostname:{{.Name}}\n"))
	tpl.Execute(os.Stdout, host)
``

https://go.dev/play/p/-CUyMyhS1pS

Thanks for the quick response!

That definitely seems to work, but it prints the hostname to the console. I was hoping to have it show up in a <p> or <h1> on the actual *.gohtml page.

Because the template renders to os.Stdout directly.

What it should show you, is that the way to use the context within the template is {{.Name}}.

For whatever else you have tried, but didn’t work, it would be nice if you would have told us, what exactly “didn’t work” means, in terms of actual output vs. expected output, whereas errs value should be part of actual/expected output.

Yeah, it printed the hostname of the container. :+1:

Nothing appeared.

Actual Output: blank
Expected Output: container_hostname

When I used $s := .Name or $s := . the actual output was $s!(nil) – something along those lines.

I resolved the issue, I was using separate ExecuteTemplate for “/” vs “/status”. Once I referenced the struct in the first ExecuteTemplate, it worked on all pages.

Thanks for the help

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