go-wise / gui.go

// Example of simple "Guest Book" desktop web application
package main

import (

const (
	port = 8765

// Guest list stored in memory for simplicity, on real application we'll
// probably want some persistence
var guestList []string

// Lock for mutating guest list
var guestLock sync.Mutex

// 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)

	defer guestLock.Unlock()
	t.Execute(w, guestList)

// addHandler add a name to the names list, then redirects back to /
func addHandler(w http.ResponseWriter, req *http.Request) {
	guest := req.FormValue("name")
	if len(guest) > 0 {
		guestList = append(guestList, guest)
		defer guestLock.Unlock()

	http.Redirect(w, req, "/", http.StatusFound)

// openBrowser waits one second and then open web browser on us
func openBrowser() {
	url := fmt.Sprintf("http://localhost:%d", port)
	exec.Command("start", url).Start()

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

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