-
Notifications
You must be signed in to change notification settings - Fork 17
/
server.go
81 lines (61 loc) · 1.47 KB
/
server.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
package main
import (
"encoding/json"
"log"
"net/http"
"strconv"
"time"
)
const commentRoute string = "/comments/"
var articles map[string]*Article
func getComments(w http.ResponseWriter, r *http.Request) {
w.Header()["Access-Control-Allow-Origin"] = []string{"*"}
idSt := r.URL.Path[len(commentRoute):]
if id, err := strconv.Atoi(idSt); err == nil {
enc := json.NewEncoder(w)
if ar, cached := arsCache[id]; cached {
enc.Encode(ar)
} else {
log.Print("Not cached")
}
} else {
log.Print(err)
}
}
func getPage(w http.ResponseWriter, r *http.Request) {
reqUrl := r.URL.Path[len("/page/"):]
w.Header()["Access-Control-Allow-Origin"] = []string{"*"}
enc := json.NewEncoder(w)
if page, cacheExists := pc.Pages[reqUrl]; cacheExists {
enc.Encode(page)
} else if reqUrl == pc.Next {
page = pc.GetNext()
enc.Encode(page)
}
}
func send(w http.ResponseWriter, r *http.Request) {
w.Header()["Access-Control-Allow-Origin"] = []string{"*"}
enc := json.NewEncoder(w)
enc.Encode(pc.Pages)
}
func reCache() {
<-time.After(30 * time.Minute)
pc = NewPageCache()
go reCache()
}
var pc *PageCache
func server(addr string) {
articles = make(map[string]*Article)
pc = NewPageCache()
for _, art := range pc.Articles {
articles[strconv.Itoa(art.Id)] = art
}
http.HandleFunc("/page/", getPage)
http.HandleFunc("/", send)
http.HandleFunc(commentRoute, getComments)
err := http.ListenAndServe(addr, nil)
if err != nil {
log.Fatal(err)
}
go reCache()
}