post image :date_long | 1 min Read

Go request.FormValue('x') with ExecuteTemplate(...)

package main

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


var tpl *template.Template

type person struct {
	FirstName   string
	LastName    string
	Subscribed  bool
}

func init()  {
	tpl = template.Must(template.ParseGlob("*.gohtml"))
}

func main()  {

	http.HandleFunc("/", foo)
	http.Handle("/favicon.ico", http.NotFoundHandler())
	http.ListenAndServe(":8080", nil)

}

func foo(w http.ResponseWriter, r *http.Request)  {
	f := r.FormValue("first")
	l := r.FormValue("last")
	s := r.FormValue("subscribe") == "on"

	err := tpl.ExecuteTemplate(w, "index.gohtml", person{
		FirstName:  f,
		LastName:   l,
		Subscribed: s,
	})
	if err != nil {
		http.Error(w, err.Error(), 500)
		log.Fatalln(err)
	}
}

// cat index.gohtml
// <!DOCTYPE html>
// <html lang="en">
// <head>
//     <meta charset="UTF-8">
//     <title>Input Type Submit</title>
// </head>
// <body>


// <form method="POST">
//    <label for="firstName">First Name</label>
//    <input type="text" name="first" id="firstName"><br>
//    <label for="lastName">Last Name</label>
//    <input type="text" name="last" id="lastName"><br>
//    <label for="sub">Subscribed</label>
//    <input type="checkbox" name="subscribe" id="sub"><br>
//    <input type="submit">
// </form>


// <h1>FirstName: {{.FirstName}}</h1>
// <h1>LastName: {{.LastName}}</h1>
// <h1>Subscribed: {{.Subscribed}}</h1>

// </body>
// </html>

author image

Jan Toth

I have been in DevOps related jobs for past 6 years dealing mainly with Kubernetes in AWS and on-premise as well. I spent quite a lot …

comments powered by Disqus