Skip to content

Commit 7c10984

Browse files
committed
you're doing great
1 parent 3c2a1c3 commit 7c10984

File tree

32 files changed

+603
-1
lines changed

32 files changed

+603
-1
lines changed

041_ajax/01/index.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
<script>
1818
document.querySelector('span').onclick = function () {
19-
makeRequest('test.html');
19+
makeRequest('/test.html');
2020
};
2121

2222
// STEP ONE - create a new XMLHttpRequest

041_ajax/02/01/main.go

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package main
2+
3+
import (
4+
"html/template"
5+
"net/http"
6+
"fmt"
7+
)
8+
9+
var tpl *template.Template
10+
11+
func init() {
12+
tpl = template.Must(template.ParseGlob("templates/*"))
13+
}
14+
15+
func main() {
16+
http.HandleFunc("/", index)
17+
http.HandleFunc("/foo", foo)
18+
http.ListenAndServe(":8080", nil)
19+
}
20+
21+
func index(w http.ResponseWriter, r *http.Request) {
22+
tpl.ExecuteTemplate(w, "index.gohtml", nil)
23+
}
24+
25+
func foo(w http.ResponseWriter, r *http.Request) {
26+
s := `Here is some text from foo`
27+
fmt.Fprintln(w, s)
28+
}

041_ajax/02/01/templates/index.gohtml

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>Index</title>
6+
<style>
7+
body {
8+
height: 100vh;
9+
display: flex;
10+
justify-content: center;
11+
align-items: center;
12+
}
13+
h1 {
14+
font-size: 5vw;
15+
cursor: pointer;
16+
text-decoration: underline;
17+
}
18+
</style>
19+
</head>
20+
<body>
21+
22+
23+
<h1>Make Something Happen</h1>
24+
25+
<script>
26+
document.querySelector('span').onclick = function () {
27+
makeRequest('/foo');
28+
};
29+
30+
// STEP ONE - create a new XMLHttpRequest
31+
var xhr = new XMLHttpRequest();
32+
33+
function makeRequest(url) {
34+
// make the request
35+
xhr.open('GET', url);
36+
xhr.send();
37+
// listen for the response
38+
// call receiveResponse function after we receive server response
39+
xhr.onreadystatechange = receiveResponse;
40+
}
41+
42+
function receiveResponse() {
43+
if (xhr.readyState === 4) {
44+
if (xhr.status === 200) {
45+
alert(xhr.responseText);
46+
} else {
47+
alert('There was a problem with the request.');
48+
}
49+
}
50+
}
51+
52+
</script>
53+
</body>
54+
</html>

041_ajax/02/02/main.go

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package main
2+
3+
import (
4+
"html/template"
5+
"net/http"
6+
"fmt"
7+
)
8+
9+
var tpl *template.Template
10+
11+
func init() {
12+
tpl = template.Must(template.ParseGlob("templates/*"))
13+
}
14+
15+
func main() {
16+
http.HandleFunc("/", index)
17+
http.HandleFunc("/foo", foo)
18+
http.ListenAndServe(":8080", nil)
19+
}
20+
21+
func index(w http.ResponseWriter, r *http.Request) {
22+
tpl.ExecuteTemplate(w, "index.gohtml", nil)
23+
}
24+
25+
func foo(w http.ResponseWriter, r *http.Request) {
26+
s := `Here is some text from foo`
27+
fmt.Fprintln(w, s)
28+
}

041_ajax/02/02/templates/index.gohtml

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>Index</title>
6+
<style>
7+
body {
8+
height: 100vh;
9+
display: flex;
10+
justify-content: center;
11+
align-items: center;
12+
}
13+
h1 {
14+
font-size: 5vw;
15+
cursor: pointer;
16+
text-decoration: underline;
17+
}
18+
</style>
19+
</head>
20+
<body>
21+
22+
23+
<h1>Make Something Happen</h1>
24+
25+
<script>
26+
document.querySelector('span').onclick = function () {
27+
makeRequest('/foo');
28+
};
29+
30+
// STEP ONE - create a new XMLHttpRequest
31+
var xhr = new XMLHttpRequest();
32+
33+
function makeRequest(url) {
34+
// make the request
35+
xhr.open('GET', url);
36+
xhr.send();
37+
// listen for the response
38+
// call receiveResponse function after we receive server response
39+
xhr.onreadystatechange = receiveResponse;
40+
}
41+
42+
function receiveResponse() {
43+
if (xhr.readyState === 4) {
44+
if (xhr.status === 200) {
45+
var b = document.querySelector('body');
46+
var myHeadingOne = document.createElement('h1');
47+
var myHeadingOneText = document.createTextNode(xhr.responseText);
48+
myHeadingOne.appendChild(myHeadingOneText);
49+
b.appendChild(myHeadingOne);
50+
} else {
51+
alert('There was a problem with the request.');
52+
}
53+
}
54+
}
55+
56+
</script>
57+
</body>
58+
</html>

041_ajax/03/main.go

+192
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
package main
2+
3+
import (
4+
"github.com/satori/go.uuid"
5+
"golang.org/x/crypto/bcrypt"
6+
"html/template"
7+
"net/http"
8+
"time"
9+
"fmt"
10+
"io/ioutil"
11+
)
12+
13+
type user struct {
14+
UserName string
15+
Password []byte
16+
First string
17+
Last string
18+
Role string
19+
}
20+
21+
type session struct {
22+
un string
23+
lastActivity time.Time
24+
}
25+
26+
var tpl *template.Template
27+
var dbUsers = map[string]user{} // user ID, user
28+
var dbSessions = map[string]session{} // session ID, session
29+
var dbSessionsCleaned time.Time
30+
31+
const sessionLength int = 30
32+
33+
func init() {
34+
tpl = template.Must(template.ParseGlob("templates/*"))
35+
dbSessionsCleaned = time.Now()
36+
}
37+
38+
func main() {
39+
http.HandleFunc("/", index)
40+
http.HandleFunc("/bar", bar)
41+
http.HandleFunc("/signup", signup)
42+
http.HandleFunc("/login", login)
43+
http.HandleFunc("/logout", logout)
44+
// added new route
45+
http.HandleFunc("/checkUserName", checkUserName)
46+
http.Handle("/favicon.ico", http.NotFoundHandler())
47+
http.ListenAndServe(":8080", nil)
48+
}
49+
50+
func index(w http.ResponseWriter, req *http.Request) {
51+
u := getUser(w, req)
52+
showSessions() // for demonstration purposes
53+
tpl.ExecuteTemplate(w, "index.gohtml", u)
54+
}
55+
56+
func bar(w http.ResponseWriter, req *http.Request) {
57+
u := getUser(w, req)
58+
if !alreadyLoggedIn(w, req) {
59+
http.Redirect(w, req, "/", http.StatusSeeOther)
60+
return
61+
}
62+
if u.Role != "007" {
63+
http.Error(w, "You must be 007 to enter the bar", http.StatusForbidden)
64+
return
65+
}
66+
showSessions() // for demonstration purposes
67+
tpl.ExecuteTemplate(w, "bar.gohtml", u)
68+
}
69+
70+
func signup(w http.ResponseWriter, req *http.Request) {
71+
if alreadyLoggedIn(w, req) {
72+
http.Redirect(w, req, "/", http.StatusSeeOther)
73+
return
74+
}
75+
var u user
76+
// process form submission
77+
if req.Method == http.MethodPost {
78+
// get form values
79+
un := req.FormValue("username")
80+
p := req.FormValue("password")
81+
f := req.FormValue("firstname")
82+
l := req.FormValue("lastname")
83+
r := req.FormValue("role")
84+
// username taken?
85+
if _, ok := dbUsers[un]; ok {
86+
http.Error(w, "Username already taken", http.StatusForbidden)
87+
return
88+
}
89+
// create session
90+
sID := uuid.NewV4()
91+
c := &http.Cookie{
92+
Name: "session",
93+
Value: sID.String(),
94+
}
95+
c.MaxAge = sessionLength
96+
http.SetCookie(w, c)
97+
dbSessions[c.Value] = session{un, time.Now()}
98+
// store user in dbUsers
99+
bs, err := bcrypt.GenerateFromPassword([]byte(p), bcrypt.MinCost)
100+
if err != nil {
101+
http.Error(w, "Internal server error", http.StatusInternalServerError)
102+
return
103+
}
104+
u = user{un, bs, f, l, r}
105+
dbUsers[un] = u
106+
// redirect
107+
http.Redirect(w, req, "/", http.StatusSeeOther)
108+
return
109+
}
110+
showSessions() // for demonstration purposes
111+
tpl.ExecuteTemplate(w, "signup.gohtml", u)
112+
}
113+
114+
func login(w http.ResponseWriter, req *http.Request) {
115+
if alreadyLoggedIn(w, req) {
116+
http.Redirect(w, req, "/", http.StatusSeeOther)
117+
return
118+
}
119+
var u user
120+
// process form submission
121+
if req.Method == http.MethodPost {
122+
un := req.FormValue("username")
123+
p := req.FormValue("password")
124+
// is there a username?
125+
u, ok := dbUsers[un]
126+
if !ok {
127+
http.Error(w, "Username and/or password do not match", http.StatusForbidden)
128+
return
129+
}
130+
// does the entered password match the stored password?
131+
err := bcrypt.CompareHashAndPassword(u.Password, []byte(p))
132+
if err != nil {
133+
http.Error(w, "Username and/or password do not match", http.StatusForbidden)
134+
return
135+
}
136+
// create session
137+
sID := uuid.NewV4()
138+
c := &http.Cookie{
139+
Name: "session",
140+
Value: sID.String(),
141+
}
142+
c.MaxAge = sessionLength
143+
http.SetCookie(w, c)
144+
dbSessions[c.Value] = session{un, time.Now()}
145+
http.Redirect(w, req, "/", http.StatusSeeOther)
146+
return
147+
}
148+
showSessions() // for demonstration purposes
149+
tpl.ExecuteTemplate(w, "login.gohtml", u)
150+
}
151+
152+
func logout(w http.ResponseWriter, req *http.Request) {
153+
if !alreadyLoggedIn(w, req) {
154+
http.Redirect(w, req, "/", http.StatusSeeOther)
155+
return
156+
}
157+
c, _ := req.Cookie("session")
158+
// delete the session
159+
delete(dbSessions, c.Value)
160+
// remove the cookie
161+
c = &http.Cookie{
162+
Name: "session",
163+
Value: "",
164+
MaxAge: -1,
165+
}
166+
http.SetCookie(w, c)
167+
168+
// clean up dbSessions
169+
if time.Now().Sub(dbSessionsCleaned) > (time.Second * 30) {
170+
go cleanSessions()
171+
}
172+
173+
http.Redirect(w, req, "/login", http.StatusSeeOther)
174+
}
175+
176+
func checkUserName(w http.ResponseWriter, req *http.Request) {
177+
sampleUsers := map[string]bool{
178+
179+
180+
181+
}
182+
183+
bs, err := ioutil.ReadAll(req.Body)
184+
if err != nil {
185+
fmt.Println(err)
186+
}
187+
188+
sbs := string(bs)
189+
fmt.Println("USERNAME: ", sbs)
190+
191+
fmt.Fprint(w, sampleUsers[sbs])
192+
}

0 commit comments

Comments
 (0)