-
Notifications
You must be signed in to change notification settings - Fork 45
/
player.go
91 lines (76 loc) · 1.71 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
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
package main
import (
"encoding/json"
"flag"
"log"
"net/http"
"os"
"path/filepath"
)
type Entry struct {
Name string // name of the object
IsDir bool
Mode os.FileMode
}
const (
filePrefix = "/f/"
)
var (
addr = flag.String("http", ":8080", "http listen address")
root = flag.String("root", "/home/flo/nfs/flo/Music/", "music root")
)
func main() {
flag.Parse()
http.HandleFunc("/", Index)
http.HandleFunc(filePrefix, File)
http.ListenAndServe(*addr, nil)
}
func Index(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./index.html")
log.Print("index called")
}
func File(w http.ResponseWriter, r *http.Request) {
fn := filepath.Join(*root, r.URL.Path[len(filePrefix):])
fi, err := os.Stat(fn)
log.Print("File called: ", fn)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
if fi.IsDir() {
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().(error); ok {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}()
d, err := os.Open(fn)
if err != nil {
panic(err)
}
defer d.Close()
log.Print("serverDirectory called: ", fn)
files, err := d.Readdir(-1)
if err != nil {
panic(err)
}
// Json Encode isn't working with the FileInfo interface,
// therefore populate an Array of Entry and add the Name method
entries := make([]Entry, len(files), len(files))
for k := range files {
//log.Print(files[k].Name())
entries[k].Name = files[k].Name()
entries[k].IsDir = files[k].IsDir()
entries[k].Mode = files[k].Mode()
}
j := json.NewEncoder(w)
if err := j.Encode(&entries); err != nil {
panic(err)
}
}