-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
88 lines (79 loc) · 1.57 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
package main
import (
"io"
"net/http"
"strconv"
)
func main() {
http.HandleFunc("/", authenticate)
http.Handle("/favicon.ico", http.NotFoundHandler())
http.ListenAndServe(":9000", nil)
}
func authenticate(res http.ResponseWriter, req *http.Request) {
cookie, err := req.Cookie("logged-in")
// no cookie
if err == http.ErrNoCookie {
cookie = &http.Cookie{
Name: "logged-in",
Value: "0",
}
}
// check log in
if req.Method == "POST" {
password := req.FormValue("password")
if password == "secret" {
cookie = &http.Cookie{
Name: "logged-in",
Value: "1",
}
}
}
// if logout, then logout
if req.URL.Path == "/logout" {
cookie = &http.Cookie{
Name: "logged-in",
Value: "0",
MaxAge: -1,
}
}
http.SetCookie(res, cookie)
var html string
// not logged in
if cookie.Value == strconv.Itoa(0) {
html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>LOG IN</h1>
<form method="post" action="http://localhost:9000/">
<h3>User name</h3>
<input type="text" name="userName">
<h3>Password</h3>
<input type="text" name="password">
<br>
<input type="submit">
<input type="submit" name="logout" value="logout">
</form>
</body>
</html>`
}
// logged in
if cookie.Value == strconv.Itoa(1) {
html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1><a href="http://localhost:9000/logout">LOG OUT</a></h1>
</body>
</html>`
}
io.WriteString(res, html)
}