-
Notifications
You must be signed in to change notification settings - Fork 56
/
json.go
94 lines (80 loc) · 2.44 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
package serverHandler
import (
"encoding/json"
"net/http"
"os"
"time"
)
type jsonItem struct {
IsDir bool `json:"isDir"`
Name string `json:"name"`
Size int64 `json:"size"`
ModTime time.Time `json:"modTime"`
}
type jsonResponseData struct {
NeedAuth bool `json:"needAuth"`
AuthUserName string `json:"authUserName"`
AuthSuccess bool `json:"authSuccess"`
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"`
Item *jsonItem `json:"item"`
SubItems []*jsonItem `json:"subItems"`
}
func getJsonItem(info os.FileInfo) *jsonItem {
return &jsonItem{
IsDir: info.IsDir(),
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{
NeedAuth: data.NeedAuth,
AuthUserName: data.AuthUserName,
AuthSuccess: data.AuthSuccess,
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,
Item: item,
SubItems: subItems,
}
}
func (h *aliasHandler) 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
}
w.WriteHeader(data.Status)
jsonData := getJsonData(data)
encoder := json.NewEncoder(w)
err := encoder.Encode(jsonData)
h.logError(err)
}