forked from jordic/file_server
/
main.go
227 lines (187 loc) · 5.07 KB
/
main.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package main
import (
"flag"
"fmt"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
_ "net/http/pprof"
"os"
"path"
"path/filepath"
"strings"
)
var (
dir string
port string
logging bool
depth int
auth string
debug bool
disable_sys_command bool
rootDir = "."
)
//var cpuprof string
//commandsFile string
const MAX_MEMORY = 1 * 1024 * 1024
const VERSION = "1.0"
func main() {
//fmt.Println(len(os.Args), os.Args)
if len(os.Args) > 1 && os.Args[1] == "-v" {
fmt.Println("Version " + VERSION)
os.Exit(0)
}
flag.StringVar(&dir, "dir", "/tmp", "Specify a directory to server files from.")
flag.StringVar(&port, "port", ":8080", "Port to bind the file server")
flag.BoolVar(&logging, "log", true, "Enable Log (true/false)")
flag.StringVar(&auth, "auth", "", "'username:pass' Basic Auth")
flag.IntVar(&depth, "depth", 5, "Depth directory crawler")
//flag.StringVar(&commandsFile, "commands", "", "Path to external commands file.json")
flag.BoolVar(&debug, "debug", false, "Make external assets expire every request")
flag.BoolVar(&disable_sys_command, "disable_cmd", true, "Disable sys comands")
//flag.StringVar(&cpuprof, "cpuprof", "", "write cpu and mem profile")
flag.Parse()
envDir := os.Getenv("FILESERVER_DIR")
if envDir != "" {
dir = envDir
}
envPort := os.Getenv("FILESERVER_PORT")
if envPort != "" {
port = envPort
}
envAuth := os.Getenv("FILESERVER_AUTH")
if envAuth != "" {
auth = envAuth
}
envCmd := os.Getenv("FILESERVER_COMMAND")
if envCmd != "" {
disable_sys_command = false
}
if logging == false {
log.SetOutput(ioutil.Discard)
}
// If no path is passed to app, normalize to path formath
if dir == "." {
dir, _ = filepath.Abs(dir)
}
if _, err := os.Stat(dir); err != nil {
log.Fatalf("Directory %s not exist", dir)
}
// normalize dir, ending with... /
if strings.HasSuffix(dir, "/") == false {
dir = dir + "/"
}
// build index files in background
go Build_index(dir)
mux := http.NewServeMux()
statics := &ServeStaticFromBinary{
MountPoint: "/-/assets/",
DataDir: "data/"}
mux.Handle("/-/assets/", makeGzipHandler(statics.ServeHTTP))
mux.Handle("/-/api/dirs", makeGzipHandler(http.HandlerFunc(SearchHandle)))
mux.Handle("/", BasicAuth(http.HandlerFunc(handleReq), auth))
log.Printf("Listening on port %s .....\n", port)
if debug {
log.Print("Serving data dir in debug mode.. no assets caching.\n")
}
http.ListenAndServe(port, mux)
}
func handleReq(w http.ResponseWriter, r *http.Request) {
//Is_Ajax := strings.Contains(r.Header.Get("Accept"), "application/json")
if r.Method == "PUT" {
AjaxUpload(w, r)
return
}
if r.Method == "POST" {
WebCommandHandler(w, r)
return
}
log.Print("Request: ", r.RequestURI)
// See bug #9. For some reason, don't arrive index.html, when asked it..
if strings.HasSuffix(r.URL.Path, "/") && r.FormValue("get_file") != "true" {
log.Printf("Index dir %s", r.URL.Path)
handleDir(w, r)
} else {
log.Printf("downloading file %s", path.Clean(dir+r.URL.Path))
r.Header.Del("If-Modified-Since")
http.ServeFile(w, r, path.Clean(dir+r.URL.Path))
//http.ServeContent(w, r, r.URL.Path)
//w.Write([]byte("this is a test inside file handler"))
}
}
func handleDir(w http.ResponseWriter, r *http.Request) {
var d string = ""
//log.Printf("len %d,, %s", len(r.URL.Path), dir)
if len(r.URL.Path) == 1 {
// handle root dir
d = dir
} else {
d += dir + r.URL.Path[1:]
}
// handle json format of dir...
if r.FormValue("format") == "json" {
w.Header().Set("Content-Type", "application/json")
result := &DirJson{w, d}
err := result.Get()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
if r.FormValue("format") == "zip" {
result := &DirZip{w, d}
err := result.Get()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
// If we dont receive json param... we are asking, for genric app ui...
template_file, err := Asset("data/main.html")
if err != nil {
log.Fatalf("Cant load template main")
}
t := template.Must(template.New("listing").Delims("[%", "%]").Parse(string(template_file)))
v := map[string]interface{}{
"Path": r.URL.Path,
"version": VERSION,
"sys_command": disable_sys_command,
}
w.Header().Set("Content-Type", "text/html")
t.Execute(w, v)
}
func AjaxUpload(w http.ResponseWriter, r *http.Request) {
reader, err := r.MultipartReader()
if err != nil {
fmt.Print(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
pa := r.URL.Path[1:]
for {
part, err := reader.NextPart()
if err == io.EOF {
break
}
var ff string
if dir != "." {
ff = dir + pa + part.FileName()
} else {
ff = pa + part.FileName()
}
dst, err := os.Create(ff)
defer dst.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err := io.Copy(dst, part); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
fmt.Fprint(w, "ok")
return
}