-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
177 lines (153 loc) · 4.56 KB
/
main.go
File metadata and controls
177 lines (153 loc) · 4.56 KB
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
package main
import (
"encoding/json"
"flag"
"html/template"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
type FilesResponse struct {
Directory string `json:"directory"`
Files []string `json:"files"`
Directories []string `json:"directories"`
Error string `json:"error"`
}
type ErrorResponse struct {
Message string `json:"message"`
}
var root string
func main() {
// get current path
path, err := os.Getwd()
if err != nil {
log.Fatal(path)
}
// flags
pathPtr := flag.String("path", path, "directory which will be served via HTTP")
portPtr := flag.String("port", "8000", "port on which directory will be server")
flag.Parse()
root = *pathPtr
port := *portPtr
if root == "" {
log.Fatal("FILES_DIR environment variable cannot be empty")
}
if port == "" {
log.Fatal("PORT environment varaible cannot be empty")
}
// logger format
log.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
TimestampFormat: "2006-01-02 15:04:05",
})
// endpoints
r := mux.NewRouter()
r.HandleFunc("/api/v1/file/serve/{path:.*}", serveFile).Methods("GET")
r.HandleFunc("/api/v1/directory/new", createDirectory).Methods("POST")
r.HandleFunc("/{path:.*}", index).Methods("GET", "HEAD")
http.Handle("/-/assets/", http.StripPrefix("/-/assets/", http.FileServer(http.Dir("./frontend/assets"))))
http.Handle("/", r)
log.Infof("Serving %s on port: %s", root, port)
http.ListenAndServe(":"+port, logRequest(accessControl(http.DefaultServeMux)))
}
func index(w http.ResponseWriter, r *http.Request) {
path := mux.Vars(r)["path"]
relPath := filepath.Join(root, path)
t, err := template.New("index.html").Delims("[[", "]]").ParseFiles("index.html")
if err != nil {
errRes := errorResponse(relPath, err)
t.Execute(w, errRes)
return
}
files, dirs, err := scanDir(relPath)
if err != nil {
errRes := errorResponse(relPath, err)
t.Execute(w, errRes)
return
}
res := &FilesResponse{
Directory: relPath,
Files: files,
Directories: dirs,
Error: "",
}
t.Execute(w, res)
}
func serveFile(w http.ResponseWriter, r *http.Request) {
path := mux.Vars(r)["path"]
relPath := filepath.Join(root, path)
// template
t, err := template.New("index.html").Delims("[[", "]]").ParseFiles("index.html")
if err != nil {
errRes := errorResponse(relPath, err)
t.Execute(w, errRes)
return
}
// check if file exists
if _, err := os.Stat(relPath); os.IsNotExist(err) {
errRes := errorResponse(relPath, err)
t.Execute(w, errRes)
return
}
// if mp4 file
if strings.HasSuffix(relPath, ".mp4") {
w.Header().Set("Content-Type", "video/mp4")
}
w.WriteHeader(http.StatusOK)
http.ServeFile(w, r, relPath)
}
func createDirectory(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
response := make(map[string]interface{})
path := r.PostFormValue("path")
newDirName := r.PostFormValue("dir_name")
if newDirName == "" {
w.WriteHeader(http.StatusInternalServerError)
response["error"] = "Unable to create directory"
response["new_directory"] = newDirName
json.NewEncoder(w).Encode(response)
return
}
dirPath := filepath.Join(root, path, newDirName) // new folder path
if _, err := os.Stat(dirPath); !os.IsNotExist(err) {
w.WriteHeader(http.StatusInternalServerError)
response["error"] = "Directory " + dirPath + " already exists"
json.NewEncoder(w).Encode(response)
return
}
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
if err := os.Mkdir(dirPath, 0777); err != nil {
w.WriteHeader(http.StatusInternalServerError)
response["error"] = err.Error()
json.NewEncoder(w).Encode(response)
return
}
log.Infof("Created new dir: %s", dirPath)
}
response["message"] = "Successfully created new directory"
response["new_directory"] = dirPath
json.NewEncoder(w).Encode(response)
}
func logRequest(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
func accessControl(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS, POST, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization")
if r.Method == "OPTIONS" {
return
}
h.ServeHTTP(w, r)
})
}
func errorResponse(relPath string, err error) *FilesResponse {
return &FilesResponse{relPath, []string{}, []string{}, err.Error()}
}