-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
101 lines (90 loc) · 2.11 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net/http"
"sort"
"strconv"
)
type (
Attr struct {
Id NodeID `json:"id"`
}
DisplayNode struct {
Data string `json:"data"`
State string `json:"state"`
Attr Attr `json:"attr"`
size ByteSize
}
)
func tree(w http.ResponseWriter, r *http.Request, store Storage, root NodeID) {
id, err := strconv.ParseUint(r.FormValue("id"), 10, 64)
if err != nil {
leaf(w, store, root)
} else {
leaves(w, store, NodeID(id))
}
}
func leaf(w http.ResponseWriter, store Storage, n NodeID) {
val, err := store.Retrieve(n)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
node := DisplayNode{fmt.Sprintf("%s %s", val.name, val.data), "closed", Attr{val.id}, val.data}
b, err := json.Marshal(node)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(b)
}
func leaves(w http.ResponseWriter, store Storage, n NodeID) {
val, err := store.Retrieve(n)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
children := make([]DisplayNode, len(val.children))
for j, c := range val.children {
cval, err := store.Retrieve(c)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var state string
if len(cval.children) != 0 {
state = "closed"
} else {
state = "x"
}
children[j] = DisplayNode{
fmt.Sprintf("%s %s", cval.name, cval.data),
state, Attr{cval.id}, cval.data}
}
// Sort nodes by size
sort.Sort(DisplayNodeSlice(children))
b, err := json.Marshal(children)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(b)
}
func index(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, r.URL.Path[1:])
}
func main() {
flag.Parse()
var store mapStore = make(map[NodeID]Result)
data := du(flag.Arg(0), flag.Arg(0), store)
http.HandleFunc("/", index)
http.HandleFunc("/tree", func(w http.ResponseWriter, r *http.Request) {
tree(w, r, store, data.id)
})
addr := ":8080"
log.Println("Listening on", addr)
http.ListenAndServe(addr, nil)
}