-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
92 lines (76 loc) · 2.05 KB
/
handlers.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
package main
import (
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
)
// Show the file and directory views.
func browseFilesHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// The new path is the base path + the requested path
// The server accepts paths relative to the base
currentPath := ensureDirPath(basePath + r.URL.Path)
// Ensure that the path exists on the system
dir, err := ioutil.ReadDir(currentPath)
if err != nil {
http.Error(w, "Invalid location", http.StatusInternalServerError)
return
}
// Convert os.FileInfo to fileInfo
contents := make([]FileInfo, 0)
for _, val := range dir {
if !*showDots && val.Name()[0] == '.' {
continue
}
temp := FileInfo{
Info: val,
Link: ensureDirPath(r.URL.Path) + val.Name(),
DownloadLink: "/download" + ensureDirPath(r.URL.Path) + val.Name(),
FDate: val.ModTime().Format(time.UnixDate),
DirSize: -1,
}
if temp.Info.IsDir() {
temp.DirSize = getDirSize(currentPath + temp.Info.Name())
}
contents = append(contents, temp)
}
headerName := strings.Split(r.URL.Path, "/")
// Execute template with newly created Directory object
err = tmpl.Execute(w, Directory{
Name: headerName[len(headerName)-1],
Path: basePath,
RelativePath: r.URL.Path,
Nav: generateNav(r.URL.Path),
Contents: contents,
})
if err != nil {
log.Fatal("Template Error: " + err.Error())
}
}
}
func downloadHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
remove := false
path := basePath + r.URL.Path[len("/download"):]
// Make sure the file exists
info, err := os.Stat(path)
if err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
// Zip directories and set path to zip file created in /tmp
if info.IsDir() {
remove = true
path = ZipWriter(path)
}
// Send the file
http.ServeFile(w, r, path)
// Only remove the temp zip file
if remove {
os.Remove(path)
}
}
}