Skip to content

Instantly share code, notes, and snippets.

@tux21b
Created Aug 6, 2013
Embed
What would you like to do?
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