-
Notifications
You must be signed in to change notification settings - Fork 56
/
json.go
103 lines (89 loc) · 2.61 KB
/
json.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
package serverHandler
import (
"encoding/json"
"io"
"net/http"
"os"
"time"
)
type jsonItem struct {
IsDir bool `json:"isDir"`
IsVirtual bool `json:"isVirtual"`
Name string `json:"name"`
Size int64 `json:"size"`
ModTime time.Time `json:"modTime"`
}
type jsonResponseData struct {
IsRoot bool `json:"isRoot"`
Path string `json:"path"`
Paths []*pathEntry `json:"paths"`
SubItemPrefix string `json:"subItemPrefix"`
ContextQueryString string `json:"contextQueryString"`
CanUpload bool `json:"canUpload"`
CanMkdir bool `json:"canMkdir"`
CanDelete bool `json:"canDelete"`
CanArchive bool `json:"canArchive"`
CanCors bool `json:"canCors"`
NeedAuth bool `json:"needAuth"`
Item *jsonItem `json:"item"`
SubItems []*jsonItem `json:"subItems"`
}
func getJsonItem(info os.FileInfo) *jsonItem {
return &jsonItem{
IsDir: info.IsDir(),
IsVirtual: isVirtual(info),
Name: info.Name(),
Size: info.Size(),
ModTime: info.ModTime(),
}
}
func getJsonData(data *responseData) *jsonResponseData {
var item *jsonItem
var subItems []*jsonItem
if data.Item != nil {
item = getJsonItem(data.Item)
}
subItems = make([]*jsonItem, len(data.SubItems))
for i := range data.SubItems {
subItems[i] = getJsonItem(data.SubItems[i])
}
return &jsonResponseData{
IsRoot: data.IsRoot,
Path: data.Path,
Paths: data.Paths,
SubItemPrefix: data.SubItemPrefix,
ContextQueryString: data.Context.QueryString(),
CanUpload: data.CanUpload,
CanMkdir: data.CanMkdir,
CanDelete: data.CanDelete,
CanArchive: data.CanArchive,
CanCors: data.CanCors,
NeedAuth: data.NeedAuth,
Item: item,
SubItems: subItems,
}
}
func (h *handler) json(w http.ResponseWriter, r *http.Request, data *responseData) {
header := w.Header()
header.Set("Content-Type", "application/json; charset=utf-8")
header.Set("Cache-Control", "public, max-age=0")
if !needResponseBody(r.Method) {
w.WriteHeader(data.Status)
return
}
var bodyW io.Writer
if compressW, encoding, useCompressW := getCompressWriter(w, r); useCompressW {
header.Set("Content-Encoding", encoding)
bodyW = compressW
defer compressW.Close()
} else {
bodyW = w
}
w.WriteHeader(data.Status)
jsonData := getJsonData(data)
encoder := json.NewEncoder(bodyW)
err := encoder.Encode(jsonData)
if err != nil {
go h.errHandler.LogError(err)
}
}