This repository has been archived by the owner on Nov 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
86 lines (72 loc) · 1.78 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
83
84
85
86
package main
import (
"github.com/satori/go.uuid"
"html/template"
"net/http"
)
type user struct {
UserName string
Password string
First string
Last string
}
var tpl *template.Template
var dbUsers = map[string]user{} // user ID, user
var dbSessions = map[string]string{} // session ID, user ID (email)
func init() {
tpl = template.Must(template.ParseGlob("templates/*.gohtml"))
}
func main() {
http.HandleFunc("/", index)
http.HandleFunc("/signup", signup)
http.HandleFunc("/bar", bar)
http.Handle("/favicon.ico", http.NotFoundHandler())
http.ListenAndServe(":8080", nil)
}
func index(w http.ResponseWriter, r *http.Request) {
u := getUser(w, r)
tpl.ExecuteTemplate(w, "index.gohtml", u)
}
func signup(w http.ResponseWriter, r *http.Request) {
if alreadyLoggedIn(r) {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
// process form submission
if r.Method == http.MethodPost {
e := r.FormValue("email")
p := r.FormValue("password")
f := r.FormValue("first")
l := r.FormValue("last")
// is username taken, eg, user already signed up?
if _, ok := dbUsers[e]; ok {
http.Error(w, "Username already taken", http.StatusForbidden)
return
}
// create session
id := uuid.NewV4()
c := &http.Cookie{
Name: "session",
Value: id.String(),
HttpOnly: true,
Path: "/",
}
http.SetCookie(w, c)
dbSessions[c.Value] = e
// store user in dbUsers
u := user{e, p, f, l}
dbUsers[e] = u
// all done processing form submission
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
tpl.ExecuteTemplate(w, "signup.gohtml", nil)
}
func bar(w http.ResponseWriter, r *http.Request) {
if !alreadyLoggedIn(r) {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
u := getUser(w, r)
tpl.ExecuteTemplate(w, "bar.gohtml", u)
}