Skip to content

Commit 00ed5aa

Browse files
committed
feat(serverHandler): output json data if param is "json" for file list
1 parent ed1b46a commit 00ed5aa

File tree

3 files changed

+76
-3
lines changed

3 files changed

+76
-3
lines changed

src/serverHandler/json.go

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package serverHandler
2+
3+
import (
4+
"encoding/json"
5+
"net/http"
6+
"os"
7+
"time"
8+
)
9+
10+
type jsonItem struct {
11+
IsDir bool `json:"isDir"`
12+
Name string `json:"name"`
13+
Size int64 `json:"size"`
14+
ModTime time.Time `json:"modTime"`
15+
}
16+
17+
type jsonResponseData struct {
18+
Item *jsonItem `json:"item"`
19+
SubItems []*jsonItem `json:"subItems"`
20+
}
21+
22+
func getJsonItem(info os.FileInfo) *jsonItem {
23+
return &jsonItem{
24+
IsDir: info.IsDir(),
25+
Name: info.Name(),
26+
Size: info.Size(),
27+
ModTime: info.ModTime(),
28+
}
29+
}
30+
31+
func getJsonData(data *responseData) *jsonResponseData {
32+
var item *jsonItem
33+
var subItems []*jsonItem
34+
35+
if data.Item != nil {
36+
item = getJsonItem(data.Item)
37+
38+
if data.Item.IsDir() {
39+
subItems = make([]*jsonItem, len(data.SubItems))
40+
for i, dataItem := range data.SubItems {
41+
subItems[i] = getJsonItem(dataItem.Info)
42+
}
43+
}
44+
}
45+
46+
return &jsonResponseData{
47+
Item: item,
48+
SubItems: subItems,
49+
}
50+
}
51+
52+
func (h *handler) json(w http.ResponseWriter, r *http.Request, data *responseData) {
53+
header := w.Header()
54+
header.Set("Content-Type", "application/json; charset=utf-8")
55+
header.Set("Cache-Control", "public, max-age=0")
56+
57+
if data.hasInternalError {
58+
w.WriteHeader(http.StatusInternalServerError)
59+
} else if data.hasNotFoundError {
60+
w.WriteHeader(http.StatusNotFound)
61+
} else {
62+
w.WriteHeader(http.StatusOK)
63+
}
64+
65+
if needResponseBody(r.Method) {
66+
jsonData := getJsonData(data)
67+
encoder := json.NewEncoder(w)
68+
err := encoder.Encode(jsonData)
69+
h.errHandler.LogError(err)
70+
}
71+
}

src/serverHandler/main.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,9 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
104104
}
105105

106106
item := data.Item
107-
if file != nil && item != nil && !item.IsDir() {
107+
if r.URL.RawQuery == "json" {
108+
h.json(w, r, data)
109+
} else if file != nil && item != nil && !item.IsDir() {
108110
h.content(w, r, data)
109111
} else {
110112
h.page(w, r, data)

src/serverHandler/responseData.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ import (
1313
)
1414

1515
type pathEntry struct {
16-
Name string
17-
Path string
16+
Name string `json:"name"`
17+
Path string `json:"path"`
1818
}
1919

2020
type subItemSort struct {

0 commit comments

Comments
 (0)