-
Notifications
You must be signed in to change notification settings - Fork 1
/
blackboard.go
286 lines (241 loc) · 6.48 KB
/
blackboard.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package main
// A very minimalistic web-server to handle basic files
// NO SECURITY CHECKS AT ALL !!! USE AT YOUR OWN RISK
import "github.com/gorilla/mux"
import "github.com/DavidGamba/go-getoptions"
import "net/http"
import "log"
import "time"
import "io"
import "os"
import "regexp"
import "strconv"
import "strings"
func main() {
var directory string
var listen string
var methods []string
var timeout int
opt := getoptions.New()
opt.StringVar(&directory, "directory", ``, opt.Required())
opt.StringVar(&listen, "listen", `:8000`)
opt.IntVar(&timeout, "timeout", 60)
opt.StringSliceVar(&methods, "methods", 1, 4)
remaining, err := opt.Parse(os.Args[1:])
// Handle empty or unknown options
if len(os.Args[1:]) == 0 {
log.Print(opt.Help())
os.Exit(1)
}
if err != nil {
log.Fatalf("Could not parse options: %s\n", err)
os.Exit(1)
}
if len(remaining) > 0 {
log.Fatalf("Unsupported parameter: %s\n", remaining)
os.Exit(1)
}
// By default, enable all methods
if len(methods) == 0 {
methods = append(methods, "GET")
methods = append(methods, "POST")
methods = append(methods, "PUT")
methods = append(methods, "DELETE")
methods = append(methods, "HEAD")
}
// Change to storage directory
direrr := os.Chdir(directory)
if direrr != nil {
log.Fatal("ERROR: "+direrr.Error())
os.Exit(1)
}
r := mux.NewRouter()
if contains(methods, "GET") {
r.HandleFunc("/{key}", GetHandler).Methods("GET")
}
if contains(methods, "POST") {
r.HandleFunc("/{key}", PostHandler).Methods("POST")
}
if contains(methods, "DELETE") {
r.HandleFunc("/{key}", DeleteHandler).Methods("DELETE")
}
if contains(methods, "PUT") {
r.HandleFunc("/{key}", PutHandler).Methods("PUT")
}
if contains(methods, "HEAD") {
r.HandleFunc("/{key}", HeadHandler).Methods("HEAD")
}
srv := &http.Server{
Handler: r,
Addr: listen,
// Good practice: enforce timeouts for servers you create!
WriteTimeout: time.Duration(timeout) * time.Second,
ReadTimeout: time.Duration(timeout) * time.Second,
}
log.Fatal(srv.ListenAndServe())
}
func GetHandler (w http.ResponseWriter, r *http.Request) {
endpoint := mux.Vars(r)["key"]
if (StartsWithDot(endpoint)) {
w.WriteHeader(http.StatusForbidden)
return
}
// Try to open file
fh, err := os.Open(endpoint)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
defer fh.Close()
// Automagically set Content-Type header
contentType, err2 := GetFileContentType(fh)
if err2 == nil {
w.Header().Set(`Content-Type`, contentType)
}
// Get file size for Content-Length header
stat, err3 := os.Stat(endpoint)
if err3 == nil {
w.Header().Set(`Content-Length`, strconv.FormatInt(stat.Size(), 10) )
}
// Add Last-Modified header
w.Header().Set(`Last-Modified`, LastModified(endpoint))
// Log & Return
bytes, err4 := io.Copy(w, fh)
log.Println(`GET`, endpoint, bytes, err4)
return
}
func PostHandler (w http.ResponseWriter, r *http.Request) {
endpoint := mux.Vars(r)["key"]
if (StartsWithDot(endpoint)) {
w.WriteHeader(http.StatusForbidden)
return
}
// Check if file exists, create if it does not
_, err1 := os.Stat(endpoint)
if os.IsNotExist(err1) {
os.Create(endpoint)
}
// Open for writing
fh, err := os.OpenFile(endpoint, os.O_WRONLY, 0644)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, err.Error())
return
}
defer fh.Close()
// Copy data to file
// Truncate in case previous content was longer than new content
bytes, err2 := io.Copy(fh, r.Body)
fh.Truncate(bytes)
// Log & Return
log.Println(`POST`, endpoint, bytes, err2)
return
}
func DeleteHandler (w http.ResponseWriter, r *http.Request) {
var success bool = false
endpoint := mux.Vars(r)["key"]
if (StartsWithDot(endpoint)) {
w.WriteHeader(http.StatusForbidden)
return
}
// Check if file exists
_, err1 := os.Stat(endpoint)
if os.IsNotExist(err1) {
w.WriteHeader(http.StatusNotFound)
return
}
// Remove file
err2 := os.Remove(endpoint)
if err2 == nil {
success = true
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
log.Println(`DELETE`, endpoint, success)
return
}
func GetFileContentType(out *os.File) (string, error) {
// Store current file offset
offset, _ := out.Seek(0, io.SeekCurrent)
// Only the first 512 bytes are used to sniff the content type.
buffer := make([]byte, 512)
_, err := out.Read(buffer)
if err != nil {
return "", err
}
// Restore previous offset
_, _ = out.Seek(offset, 0)
// Use the net/http package's handy DectectContentType function. Always returns a valid
// content-type by returning "application/octet-stream" if no others seemed to match.
contentType := http.DetectContentType(buffer)
return contentType, nil
}
func StartsWithDot (path string) (bool) {
match, _ := regexp.MatchString("^\\.", path)
return match
}
func PutHandler (w http.ResponseWriter, r *http.Request) {
endpoint := mux.Vars(r)["key"]
if (StartsWithDot(endpoint)) {
w.WriteHeader(http.StatusForbidden)
return
}
// Check if file exists, error if not (create == POST)
_, err1 := os.Stat(endpoint)
if os.IsNotExist(err1) {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
// Open for writing
fh, err := os.OpenFile(endpoint, os.O_WRONLY, 0644)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, err.Error())
return
}
defer fh.Close()
// Copy data to file
// Truncate in case previous content was longer than new content
bytes, err2 := io.Copy(fh, r.Body)
fh.Truncate(bytes)
// Log & Return
log.Println(`PUT`, endpoint, bytes, err2)
return
}
func contains (slice []string, item string) (bool) {
for _, s := range slice {
if strings.EqualFold(s, item) {
return true
}
}
return false
}
func HeadHandler (w http.ResponseWriter, r *http.Request) {
endpoint := mux.Vars(r)["key"]
if (StartsWithDot(endpoint)) {
w.WriteHeader(http.StatusForbidden)
return
}
// Try to open file
fh, err := os.Open(endpoint)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
defer fh.Close()
// Add Last-Modified header
w.Header().Set(`Last-Modified`, LastModified(endpoint))
log.Println(`HEAD`, endpoint)
return
}
func LastModified (filename string) (string) {
fh, err := os.Open(filename)
if err == nil {
defer fh.Close()
} else {
return ``
}
statinfo, _ := fh.Stat()
return statinfo.ModTime().UTC().Format(http.TimeFormat)
}