forked from nf/goplayer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayer.go
72 lines (65 loc) · 1.43 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
package main
import (
"encoding/json"
"flag"
"log"
"net/http"
"os"
)
const (
filePrefix = "/f/"
)
var (
addr = flag.String("http", ":8080", "http listen address")
root = flag.String("root", "/Volumes/media/Music/", "music root")
)
func main() {
flag.Parse()
http.HandleFunc("/", Index)
log.Printf("About to listen on 8080. Go to https://localhost:8080/")
http.HandleFunc(filePrefix, File)
// http.ListenAndServe(*addr, nil)
err := http.ListenAndServeTLS(*addr, "moderation-cert.pem", "moderation-key.pem", nil)
if err != nil {
log.Fatal(err)
}
}
func Index(w http.ResponseWriter, r *http.Request) {
log.Println("Request:", r)
log.Println("Response:", w)
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.Error(), http.StatusNotFound)
return
}
if fi.IsDirectory() {
serveDirectory(fn, w, r)
return
}
log.Println("Request:", r)
log.Println("Response:", w)
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)
}
files, err := d.Readdir(-1)
if err != nil {
panic(err)
}
j := json.NewEncoder(w)
if err := j.Encode(files); err != nil {
panic(err)
}
}