forked from nf/goplayer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayer.go
64 lines (56 loc) · 1.16 KB
/
player.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
package main
import (
"flag"
"http"
"json"
"os"
)
const (
filePrefix = "/f/"
)
var (
addr = flag.String("http", ":8080", "http listen address")
root = flag.String("root", "/home/ton/Music/", "music root")
)
func main() {
flag.Parse()
http.HandleFunc("/", Index)
http.HandleFunc(filePrefix, File)
http.ListenAndServe(":8080", nil)
}
func Index(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
http.ServeFile(w, r, "index.html")
}
func File(w http.ResponseWriter, r *http.Request) {
fn := *root + r.URL.Path[len(filePrefix):]
fi, err := os.Stat(fn)
if err != nil {
http.Error(w, err.String(), http.StatusNotFound)
return
}
if fi.IsDirectory() {
serveDirectory(fn, w, r)
return
}
http.ServeFile(w, r, fn)
}
func serveDirectory(fn string, w http.ResponseWriter, r *http.Request) {
defer func() {
if err, ok := recover().(os.Error); ok {
http.Error(w, err.String(), http.StatusInternalServerError)
}
}()
d, err := os.Open(fn)
if err != nil {
panic(err)
}
files, err := d.Readdir(-1)
if err != nil {
panic(err)
}
j := json.NewEncoder(w)
if err := j.Encode(files); err != nil {
panic(err)
}
}