-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
74 lines (62 loc) · 1.89 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//go:generate go run assets_gen.go assets.go
// Gopherpen is a project template that will let you easily get started with GopherJS
// for building a web app. It includes some simple HTML, CSS, and Go code for the frontend.
// Make some changes, and refresh in browser to see results. When there are errors in your
// frontend Go code, they will show up in the browser console.
//
// Once you're done making changes, you can easily create a fully self-contained static
// production binary.
package main
import (
"flag"
"fmt"
"html/template"
"log"
"net/http"
"strings"
"github.com/shurcooL/httpfs/html/vfstemplate"
"github.com/shurcooL/httpgzip"
)
var httpFlag = flag.String("http", ":8080", "Listen for HTTP connections on this address.")
func loadTemplates() (*template.Template, error) {
t := template.New("").Funcs(template.FuncMap{})
t, err := vfstemplate.ParseGlob(assets, t, "/assets/*.tmpl")
return t, err
}
func mainHandler(w http.ResponseWriter, req *http.Request) {
t, err := loadTemplates()
if err != nil {
log.Println("loadTemplates:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var data = struct {
Animals string
}{
Animals: "gophers",
}
err = t.ExecuteTemplate(w, "index.html.tmpl", data)
if err != nil {
log.Println("t.Execute:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func main() {
flag.Parse()
http.HandleFunc("/", mainHandler)
http.Handle("/assets/", httpgzip.FileServer(assets, httpgzip.FileServerOptions{ServeError: httpgzip.Detailed}))
http.Handle("/favicon.ico", http.NotFoundHandler())
printServingAt(*httpFlag)
err := http.ListenAndServe(*httpFlag, nil)
if err != nil {
log.Fatalln("ListenAndServe:", err)
}
}
func printServingAt(addr string) {
hostPort := addr
if strings.HasPrefix(hostPort, ":") {
hostPort = "localhost" + hostPort
}
fmt.Printf("serving at http://%s/\n", hostPort)
}