How To Call A Variable From Main.go File To An Html File?
In this code, I have an about function in main.go in which I am trying to get the Content variable data in about.html. I called {{.Content}} in about.html but it shows no result wh
Solution 1:
following is a test implementation of given OP code.
I use a go1.15 usng GOPATH, set myself under test/d/htt
.
I will only fix your handler, by adding the content variable to the template arguments, and its going to work.
$ touch main.go$ touch handler.go$ touch handler_test.go$ mkdir -p ui/html$ touch ui/html/about.html$ touch ui/html/footer.html$ touch ui/html/base.html
main.go
package main
import (
"html/template""log""net/http"
)
funcmakeTemlate(base string) *template.Template {
files := []string{base, "ui/html/footer.html", "ui/html/base.html"}
return template.Must(template.ParseFiles(files...))
}
funcmain() {
http.HandleFunc("/about", About)
log.Println("Starting the server at :4000")
http.ListenAndServe(":4000", nil)
}
handler.go
package main
import (
"net/http"
)
var aboutTmpl = makeTemlate("ui/html/about.html")
type Details struct {
Success bool
Content string
}
funcAbout(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
aboutTmpl.Execute(w, nil)
return
}
details := Details{
Success: true,
Content: r.FormValue("content"),
}
aboutTmpl.Execute(w, details)
}
handler_test.go
package main
import (
"bytes""io""net/http""net/http/httptest""net/url""strings""testing"
)
funcTestAboutHandlerGetMethod(t *testing.T) {
req, err := http.NewRequest("GET", "/about", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
handler := http.HandlerFunc(About)
handler.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
var buf bytes.Buffer
io.Copy(&buf, rr.Body)
b := buf.Bytes()
if !bytes.Contains(b, []byte(`<form action="/about" method="POST" name="about" id="about">`)) {
t.Errorf("form must be displayed when fetch with GET method, got=\n%s", b)
}
}
funcTestAboutHandlerPostMethod(t *testing.T) {
form := url.Values{}
form.Add("content", "Hellocontent")
req, err := http.NewRequest("POST", "/about", strings.NewReader(form.Encode()))
if err != nil {
t.Fatal(err)
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
rr := httptest.NewRecorder()
handler := http.HandlerFunc(About)
handler.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
var buf bytes.Buffer
io.Copy(&buf, rr.Body)
b := buf.Bytes()
if bytes.Contains(b, []byte(`<form action="/about" method="POST" name="about" id="about">`)) {
t.Errorf("form must not be displayed when fetch with POST method, got=\n%s", b)
}
if !bytes.Contains(b, []byte(`Hellocontent`)) {
t.Errorf("output must include the dispay of the posted content, got=\n%s", b)
}
}
ui/html/base.html
{{define "base"}}
{{template"title" .}}
{{template"body" .}}
{{end}}
ui/html/about.html
{{template "base" .}}
{{define "title"}} About {{end}}
{{define "body"}}
{{if .Success}}
{{.Content}}
{{else}}
<h1>About</h1>
<formaction="/about"method="POST"name="about"id="about"><div><label>Content</label><textareaname="content"></textarea></div><div><inputtype="submit"value="Submit"></div></form>
{{end}}
{{end}}
ui/html/footer.html
// left empty...
Finally, i run go test -v .
=== RUN TestAboutHandlerGetMethod--- PASS: TestAboutHandlerGetMethod (0.00s)=== RUN TestAboutHandlerPostMethod--- PASS: TestAboutHandlerPostMethod (0.00s)
PASS
ok test/d/htt 0.005s
Final notes, the http post test can be written using http.PostForm
, for simplification and dryness, https://pkg.go.dev/net/http#PostForm
Post a Comment for "How To Call A Variable From Main.go File To An Html File?"