-
Notifications
You must be signed in to change notification settings - Fork 0
/
player.go
77 lines (65 loc) · 1.46 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
package main
import (
"encoding/json"
"net/http"
"os"
"path/filepath"
)
// FileInfo structure
type FileInfo struct {
Name string
IsDir bool
Mode os.FileMode
}
const (
filePrefix = "/music/"
root = "./music"
)
func main() {
http.HandleFunc("/", playerMainFrame)
http.HandleFunc(filePrefix, File)
http.ListenAndServe(":8080", nil)
}
func playerMainFrame(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./player.html")
}
// File function
func File(w http.ResponseWriter, r *http.Request) {
path := filepath.Join(root, r.URL.Path[len(filePrefix):])
stat, err := os.Stat(path)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
if stat.IsDir() {
serveDir(w, r, path)
return
}
http.ServeFile(w, r, path)
}
func serveDir(w http.ResponseWriter, r *http.Request, path string) {
defer func() {
if err, ok := recover().(error); ok {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}()
file, err := os.Open(path)
defer file.Close()
if err != nil {
panic(err)
}
files, err := file.Readdir(-1)
if err != nil {
panic(err)
}
fileinfos := make([]FileInfo, len(files), len(files))
for i := range files {
fileinfos[i].Name = files[i].Name()
fileinfos[i].IsDir = files[i].IsDir()
fileinfos[i].Mode = files[i].Mode()
}
j := json.NewEncoder(w)
if err := j.Encode(&fileinfos); err != nil {
panic(err)
}
}