-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
75 lines (59 loc) · 1.42 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
75
package main
import (
"html/template"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/gorilla/handlers"
)
var hitCounter uint
var signatures []Signature
// Signature represents a signature!
type Signature struct {
Name string
Timestamp time.Time
}
func guestbookHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
// Handle a new signature being posted
r.ParseForm()
name := r.Form.Get("name")
name = strings.TrimSpace(name)
if name != "" {
signatures = append(signatures, Signature{
Name: name,
Timestamp: time.Now(),
})
}
}
// Load the template
t, err := template.ParseFiles("templates/homepage.html")
if err != nil {
http.Error(w, "Error loading template", 500)
log.Printf("Error loading template: %s", err)
return
}
// Increment the hit counter
hitCounter = hitCounter + 1
data := struct {
Hits uint
Signatures []Signature
}{hitCounter, signatures}
// Render the page
if err := t.Execute(w, data); err != nil {
http.Error(w, "Error generating page", 500)
log.Printf("Error generating page: %s", err)
}
}
func getMux() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/", guestbookHandler)
mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
return mux
}
func main() {
http.Handle("/", handlers.LoggingHandler(os.Stdout, getMux()))
panic(http.ListenAndServe(":8080", nil))
}