...

/

Solution Review: Web Application for Serving Guests

Solution Review: Web Application for Serving Guests

This lesson discusses the solution to the challenge given in the previous lesson.

We'll cover the following...
package main
import (
	"fmt"
	"html/template"
	"net/http"
)

const port = 3000
var guestList []string

func main() {
	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/add", addHandler)
	http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}

// indexHandler serves the main page
func indexHandler(w http.ResponseWriter, req *http.Request) {
	t := template.New("index.html")
	t, err := t.Parse(indexHTML)
	if err != nil {
		message := fmt.Sprintf("bad template: %s", err)
		http.Error(w, message, http.StatusInternalServerError)
	}
	// the HTML output is now safe against code injection
	t.Execute(w, guestList)
}

// addHandler add a name to the names list
func addHandler(w http.ResponseWriter, req *http.Request) {
	guest := req.FormValue("name")
	if len(guest) > 0 {
		guestList = append(guestList, guest)
	}
	http.Redirect(w, req, "/", http.StatusFound)
}

var indexHTML = `
<!DOCTYPE html>
<html>
    <head>
		<title>Guest Book ::Web GUI</title>
    </head>
    <body>
		<h1>Guest Book :: Web GUI</h1>
		<form action="/add" method="post">
		Name: <input name="name" /><submit value="Sign Guest Book">
		</form>
		<hr />
		<h4>Previous Guests</h4>
		<ul>
			{{range .}}
			<li>{{.}}</li>
			{{end}}
		</ul>
	</body>
</html>
`

In the code above, The HTML for the web form is contained in the variable indexHTML, defined from line 38 to line 58. It contains an input field name at line 47. The list starting at line 51 ranges over the current values, showing them as list items.

The web server is ...