Skip to content

Instantly share code, notes, and snippets.

@tux21b
Created August 6, 2013 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tux21b/6168270 to your computer and use it in GitHub Desktop.
Save tux21b/6168270 to your computer and use it in GitHub Desktop.
package main
import (
"html/template"
"log"
"net/http"
)
var tmpl = template.Must(template.New("").Parse(`
{{define "index"}}<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<form method="POST">
<label for="name">Please enter your name:</label>
<input name="name" id="name" value="" />
<input type="submit" value="Submit" />
</form>
</body>
</html>{{end}}
{{define "greating"}}<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
<h1>Hello {{.}}!</h1>
<p><a href="/">go back</a></p>
</body>
</html>
{{end}}`))
func handleIndex(w http.ResponseWriter, r *http.Request) {
name := r.FormValue("name")
if name != "" {
if err := tmpl.ExecuteTemplate(w, "greating", name); err != nil {
log.Println("ExecuteTemplate:", err)
}
return
}
if err := tmpl.ExecuteTemplate(w, "index", nil); err != nil {
log.Println("ExecuteTemplate:", err)
}
}
func main() {
http.HandleFunc("/", handleIndex)
if err := http.ListenAndServe(":8000", nil); err != nil {
log.Fatalln("ListenAndServe:", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment