-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
90 lines (71 loc) · 1.75 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
87
88
89
90
package main
import (
"html/template"
"net/http"
uuid "github.com/satori/go.uuid"
)
type user struct {
Username string
First string
Last string
Password string
}
var tpl *template.Template
var dbUsers = map[string]user{} // user ID, user
var dbSessions = map[string]string{} // session ID, user ID
func init() {
tpl = template.Must(template.ParseGlob("templates/*"))
}
func main() {
http.HandleFunc("/", index)
http.HandleFunc("/bar", bar)
http.HandleFunc("/signup", signup)
http.Handle("/favicon.ico", http.NotFoundHandler())
http.ListenAndServe(":8080", nil)
}
func index(w http.ResponseWriter, req *http.Request) {
u := getUser(w, req)
tpl.ExecuteTemplate(w, "index.html", u)
}
func bar(w http.ResponseWriter, req *http.Request) {
u := getUser(w, req)
if !alreadyLoggedIn(req) {
http.Redirect(w, req, "/", http.StatusSeeOther)
return
}
tpl.ExecuteTemplate(w, "bar.html", u)
}
func signup(w http.ResponseWriter, req *http.Request) {
if alreadyLoggedIn(req) {
http.Redirect(w, req, "/", http.StatusSeeOther)
return
}
//process form submission
if req.Method == http.MethodPost {
// get form values
un := req.FormValue("username")
f := req.FormValue("firstname")
l := req.FormValue("lastname")
p := req.FormValue("password")
// username token?
if _, ok := dbUsers[un]; ok {
http.Error(w, "Username already taken ", http.StatusForbidden)
return
}
// create session
sID, _ := uuid.NewV4()
c := &http.Cookie{
Name: "session",
Value: sID.String(),
}
http.SetCookie(w, c)
dbSessions[c.Value] = un
// store user in dbUsers
u := user{un, f, l, p}
dbUsers[un] = u
// redirect
http.Redirect(w, req, "/bar", http.StatusSeeOther)
return
}
tpl.ExecuteTemplate(w, "signup.html", nil)
}