/
server.go
100 lines (88 loc) · 2.47 KB
/
server.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"fmt"
"github.com/wkirschbaum/quoteboard/app"
"html/template"
"io/ioutil"
"net/http"
"regexp"
"time"
)
func main() {
http.HandleFunc("/assets/", makeHandler(staticHandler))
http.HandleFunc("/", makeHandler(viewHandler))
http.HandleFunc("/quotes", makeHandler(quotesHandler))
fmt.Println("Listening on localhost:4000")
http.ListenAndServe(":4000", nil)
}
func viewHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
renderQuotePage(w)
} else if r.Method == "POST" {
storeQuote(w, r.FormValue("quote"), r.FormValue("author"))
http.Redirect(w, r, "/", 302)
}
}
func quotesHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
renderQuotes(w)
} else {
w.WriteHeader(404)
}
}
func staticHandler(w http.ResponseWriter, r *http.Request) {
content, err := ioutil.ReadFile("public" + r.URL.String())
if err == nil {
w.WriteHeader(200)
w.Write(content)
} else {
render404Page(w)
}
}
func makeHandler(fn func(http.ResponseWriter, *http.Request)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
validPathRegex := regexp.MustCompile("^/$|^/assets/\\S+$|^/quotes$")
matcher := validPathRegex.FindStringSubmatch(r.URL.Path)
if matcher == nil {
render404Page(w)
return
}
fn(w, r)
}
}
var templates = template.Must(template.ParseFiles("public/index.html", "public/404.html"))
func render404Page(w http.ResponseWriter) {
w.WriteHeader(404)
renderPage(w, "404", nil)
}
func renderQuotes(w http.ResponseWriter) {
page := app.QuotePage{Quotes: app.MakeQuoteStore().GetAllByDocumentedDateDesc()}
renderPage(w, "quotes", page)
}
func renderQuotePage(w http.ResponseWriter) {
page := app.QuotePage{Quotes: app.MakeQuoteStore().GetAllByDocumentedDateDesc()}
renderPage(w, "index", page)
}
func renderPage(w http.ResponseWriter, templateName string, object interface{}) {
devMode := true
if devMode {
t, _ := template.ParseFiles("public/" + templateName + ".html")
err := t.Execute(w, object)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
} else {
err := templates.ExecuteTemplate(w, templateName+".html", object)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
func storeQuote(w http.ResponseWriter, content string, author string) {
quote := app.Quote{
Content: content,
Author: author,
Documentor: "Unknown",
DocumentedDate: time.Now()}
app.MakeQuoteStore().Save(quote)
}