-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
185 lines (167 loc) · 3.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package main
import (
"bytes"
"encoding/gob"
"errors"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"sync"
"time"
)
type Article struct {
Id int `json:"id"`
Content string `json:"content"`
Author string `json:"author"`
}
var aMutex sync.RWMutex
var articles []*Article
const COOKIE_USER_NAME = "user_name"
func addArticle(content string, author string) {
aMutex.Lock()
defer aMutex.Unlock()
aLen := len(articles)
newArticle := Article{
Id: aLen,
Content: content,
Author: author,
}
articles = append(articles, &newArticle)
//如果当前文章条目是5的整数倍,进行备份
lenA := len(articles)
if lenA%5 == 0 && lenA != 0 {
go backupArticles()
}
}
func getArticles() []Article {
aMutex.RLock()
defer aMutex.RUnlock()
var aCopy []Article
for _, a := range articles {
aCopy = append(aCopy, *a)
}
return aCopy
}
func getUserName(rw http.ResponseWriter, r *http.Request) (userName string, err error) {
lc, err := r.Cookie(COOKIE_USER_NAME)
if err != nil || lc.Value == "" {
//去登录
rw.Header().Set("Location", "/login")
rw.WriteHeader(301)
err = errors.New("need login")
return
}
userName = lc.Value
return
}
func doLogin(rw http.ResponseWriter, user string) {
lc := http.Cookie{
Name: COOKIE_USER_NAME,
Value: user,
}
rw.Header().Set("Set-Cookie", lc.String())
}
func unLogin(rw http.ResponseWriter) {
lc := http.Cookie{
Name: COOKIE_USER_NAME,
Value: "",
Expires: time.Unix(1, 0),
MaxAge: -1,
}
rw.Header().Set("Set-Cookie", lc.String())
}
func login(rw http.ResponseWriter, r *http.Request) {
t := template.Must(template.ParseFiles("login.html"))
t.Execute(rw, nil)
}
func loginCheck(rw http.ResponseWriter, r *http.Request) {
un := r.PostFormValue("user_name")
p := r.PostFormValue("password")
if un == "" && p == "" {
log.Fatal(errors.New("user name and password is empty"))
}
doLogin(rw, un)
rw.Header().Set("Location", "/all_articles")
rw.WriteHeader(301)
}
func allArticles(rw http.ResponseWriter, r *http.Request) {
data := struct {
UserName string
Articles []Article
}{}
data.Articles = getArticles()
un, err := getUserName(rw, r)
if err != nil {
fmt.Println(err)
rw.Header().Set("Location", "/login")
rw.WriteHeader(301)
return
}
data.UserName = un
t := template.Must(template.ParseFiles("articles.html"))
t.Execute(rw, data)
}
func addArticleHandle(rw http.ResponseWriter, r *http.Request) {
content := r.PostFormValue("content")
author, err := getUserName(rw, r)
if err != nil {
fmt.Println(err)
return
}
addArticle(content, author)
rw.Header().Set("Location", "/all_articles")
rw.WriteHeader(301)
}
func exitHandle(rw http.ResponseWriter, r *http.Request) {
unLogin(rw)
rw.Header().Set("Location", "/login")
rw.WriteHeader(301)
}
const DATA_FILE = "data.gob"
func backupArticles() {
as := getArticles()
buf := new(bytes.Buffer)
encoder := gob.NewEncoder(buf)
err := encoder.Encode(as)
if err != nil {
panic(err)
}
bs := buf.Bytes()
err = ioutil.WriteFile(DATA_FILE, bs, 0644)
if err != nil {
panic(err)
}
}
func getArticlesByBackup() []Article {
as := make([]Article, 0)
bs, err := ioutil.ReadFile(DATA_FILE)
if err != nil {
//文件不存在,返回空切片
return as
}
buf := bytes.NewBuffer(bs)
decoder := gob.NewDecoder(buf)
err = decoder.Decode(&as)
if err != nil {
panic(err)
}
return as
}
func main() {
//如果存在备份数据,加载
as := getArticlesByBackup()
if len(as) > 0 {
for _, a := range as {
a := a
articles = append(articles, &a)
}
}
http.HandleFunc("/login", login)
http.HandleFunc("/login_check", loginCheck)
http.HandleFunc("/all_articles", allArticles)
http.HandleFunc("/add_article", addArticleHandle)
http.HandleFunc("/exit", exitHandle)
http.ListenAndServe(":8080", nil)
}