-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
111 lines (84 loc) · 2.33 KB
/
server.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
package ikdoc
import (
"net/http"
"strings"
"path/filepath"
"path"
"os"
"fmt"
"io"
"github.com/fsnotify/fsnotify"
"time"
badrand "math/rand"
log "github.com/sirupsen/logrus"
)
func servefile(f *os.File, w http.ResponseWriter, r *http.Request) {
d, err := f.Stat()
if err != nil {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
w.Header().Set("Content-Length", fmt.Sprintf("%d", d.Size()))
io.CopyN(w, f, d.Size())
}
func wait(ikchaindir string) {
watcher, err := fsnotify.NewWatcher()
if err != nil { panic(err) }
defer watcher.Close()
err = watcher.Add(ikchaindir)
if err != nil { panic(err ) }
select {
case <- watcher.Events:
case err, _ := <- watcher.Errors:
log.Println(err)
}
}
func Server(ikchaindir string) http.Handler {
notify := make(chan struct{})
go func() {
for ;;{
wait(ikchaindir)
close(notify)
notify = make(chan struct{})
}
}()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
upath := path.Clean("/" + r.URL.Path)
if strings.Contains(upath, "..") {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
if strings.HasPrefix(upath, "/.ikchain/") {
upath = r.URL.Path[len("/.ikchain/"):]
}
upath = filepath.Join(ikchaindir, filepath.FromSlash(upath))
log.Println("[ikserv] request for", upath);
f, err := os.Open(upath)
if err == nil {
defer f.Close()
servefile(f, w, r)
return
}
if r.Header.Get("Wait") != "" {
dur, _ := time.ParseDuration(r.Header.Get("Wait"))
if dur < time.Second {
dur = time.Second
}
if dur > time.Minute {
dur = time.Minute
}
select {
case <- notify:
case <- time.After(dur + time.Millisecond * time.Duration(badrand.Intn(100))):
}
f, err := os.Open(upath)
if err == nil {
defer f.Close()
servefile(f, w, r)
return
}
}
http.Error(w, "Not Found", http.StatusNotFound)
return
})
}