go-wise / gui.go

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

import (
	"fmt"
	"html/template"
	"net/http"
	"os/exec"
	"sync"
	"time"
)

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

	guestLock.Lock()
	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 {
		guestLock.Lock()
		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() {
	time.Sleep(time.Second)
	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>
<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" id="name" /><submit value="Sign Guest Book">
		</form>
		<hr />
		<h4>Previous Guests</h4>
		<ul>
			{{range .}}
			<li>{{.}}</li>
			{{end}}
		</ul>
	</body>
	<script>
		document.getElementById('name').focus();
	</script>
</html>
`
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.