-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
85 lines (68 loc) · 1.48 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
package main
import (
"fmt"
"html/template"
"net/http"
guuid "github.com/google/uuid"
)
type user struct {
UserName string
First string
Last string
}
var tpl *template.Template
var dbUsers = map[string]user{}
var dbSessions = map[string]string{}
func init() {
tpl = template.Must(template.ParseGlob("templates/*"))
}
func main() {
http.HandleFunc("/", foo)
http.HandleFunc("/bar", bar)
http.ListenAndServe(":8080", nil)
}
func foo(w http.ResponseWriter, req *http.Request) {
//get cookie
c, err := req.Cookie("session")
if err != nil {
sID := guuid.New()
c = &http.Cookie{
Name: "session",
Value: sID.String(),
// secure true
HttpOnly: true,
}
http.SetCookie(w, c)
fmt.Printf("this is my unique id: %s\n", sID.String())
}
// if the user already exists
var u user
if un, ok := dbSessions[c.Value]; ok {
u = dbUsers[un]
}
// process form submission
if req.Method == http.MethodPost {
un := req.FormValue("username")
f := req.FormValue("firstname")
l := req.FormValue("lastname")
u = user{un, f, l}
dbSessions[c.Value] = un
dbUsers[un] = u
}
tpl.ExecuteTemplate(w, "index.gohtml", u)
}
func bar(w http.ResponseWriter, req *http.Request) {
// get cookie
c, err := req.Cookie("session")
if err != nil {
http.Redirect(w, req, "/", http.StatusSeeOther)
return
}
un, ok := dbSessions[c.Value]
if !ok {
http.Redirect(w, req, "/", http.StatusSeeOther)
return
}
u := dbUsers[un]
tpl.ExecuteTemplate(w, "bar.gohtml", u)
}