-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
111 lines (95 loc) · 2.71 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"fmt"
"html/template"
"net/http"
"time"
"github.com/google/uuid"
)
//Client are type for form field on frontend
type client struct {
Username string
Firstname string
Lastname string
}
var tpl *template.Template
//DBsess for session user
var DBsess = map[string]string{} //session ID, User ID
//DBuser for user
var DBuser = map[string]client{} //user ID, user
func init() {
tpl = template.Must(template.ParseGlob("./templates/*.html"))
}
func main() {
http.Handle("/favicon.ico", http.NotFoundHandler())
http.HandleFunc("/", foo)
http.HandleFunc("/bar", bar)
http.HandleFunc("/doo", doo)
http.ListenAndServe(":8080", nil)
}
func foo(w http.ResponseWriter, r *http.Request) {
d := uuid.New()
c, err := r.Cookie("_sess")
//if client already has a cookie this code will be skipped and go to get a user
if err == http.ErrNoCookie {
c = &http.Cookie{
Name: "_sess",
Value: d.String(),
HttpOnly: true,
Expires: time.Now().Add(time.Hour * 24 * 365), //1 year
}
http.SetCookie(w, c)
}
//get user
var dataUser client
username, status := DBsess[c.Value] // res contained status true or false //xxxxxxxx
fmt.Println(username, status)
if status == true {
dataUser = DBuser[username] //zzzzzz
}
fmt.Println("line 55 --- Data user is :", dataUser)
fmt.Println("line 56 --- username is :", username)
//process submission
if r.Method == http.MethodPost {
uForm := r.FormValue("username")
fForm := r.FormValue("firstname")
lForm := r.FormValue("lastname")
dataUser = client{
uForm,
fForm,
lForm,
}
DBsess[c.Value] = uForm //map[xxxxxxxx-xxxxx-xxxxx-xxxxx-xxxxxxxxxxxxx: username]
DBuser[uForm] = dataUser //map:{username: username firstname lastname}
}
fmt.Println("line 73 --- DBsess is :", DBsess)
fmt.Println("line 74 --- DBuser is :", DBuser)
tpl.ExecuteTemplate(w, "index.html", dataUser)
}
func bar(w http.ResponseWriter, r *http.Request) {
//get cookie
c, err := r.Cookie("_sess")
if err != nil {
http.Redirect(w, r, "/", 303) //http.StatusSeeOther
return
}
username, status := DBsess[c.Value] //status contained status true or false
if status != true {
fmt.Println("usname line 89", username)
fmt.Println("status line 89", status)
http.Redirect(w, r, "/", 303) //http.StatusSeeOther
return
}
dataUser := DBuser[username]
tpl.ExecuteTemplate(w, "bar.html", dataUser)
}
func doo(w http.ResponseWriter, r *http.Request) {
c, err := r.Cookie("_sess")
if err != nil {
http.Redirect(w, r, "/", 303) //http.StatusSeeOther
return
}
c.MaxAge = -1
http.SetCookie(w, c)
http.Redirect(w, r, "/", 303) //http.StatusSeeOther
}