forked from apex/up-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
82 lines (67 loc) · 1.51 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
76
77
78
79
80
81
82
package main
import (
"html/template"
"net/http"
"os"
"github.com/apex/log"
"github.com/apex/log/handlers/json"
"github.com/apex/log/handlers/text"
)
var views = template.Must(template.ParseGlob("views/*.html"))
// use JSON logging when run by Up (including `up start`).
func init() {
if os.Getenv("UP_STAGE") == "" {
log.SetHandler(text.Default)
} else {
log.SetHandler(json.Default)
}
}
// setup.
func main() {
addr := ":" + os.Getenv("PORT")
http.HandleFunc("/submit", submit)
http.HandleFunc("/", index)
if err := http.ListenAndServe(addr, nil); err != nil {
log.Fatalf("error listening: %s", err)
}
}
// index page.
func index(w http.ResponseWriter, r *http.Request) {
name := cookie(r, "name")
email := cookie(r, "email")
w.Header().Set("Content-Type", "text/html")
views.ExecuteTemplate(w, "index.html", struct {
Name string
Email string
}{
Name: name,
Email: email,
})
}
// submit handler.
func submit(w http.ResponseWriter, r *http.Request) {
name := r.FormValue("name")
email := r.FormValue("email")
log.WithFields(log.Fields{
"name": name,
"email": email,
}).Info("submit")
http.SetCookie(w, &http.Cookie{
Name: "name",
Value: name,
})
redirectBack(w, r)
}
// redirect to referrer helper.
func redirectBack(w http.ResponseWriter, r *http.Request) {
url := r.Header.Get("Referer")
http.Redirect(w, r, url, http.StatusFound)
}
// cookie helper.
func cookie(r *http.Request, name string) string {
c, err := r.Cookie(name)
if err != nil {
return ""
}
return c.Value
}