-
Notifications
You must be signed in to change notification settings - Fork 1
/
media.go
55 lines (46 loc) · 994 Bytes
/
media.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
package main
import (
"errors"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"github.com/pdxgo/whispering-gophers/util"
)
// Open launches server from the media file.
func Open(name string) (string, error) {
path, err := filepath.Abs(name)
if err != nil {
return "", err
}
f, err := os.Open(path)
defer f.Close()
if err != nil {
return "", err
}
stat, err := f.Stat()
if err != nil {
return "", err
}
switch mode := stat.Mode(); {
case mode.IsDir():
return "", errors.New("directory is unsupported")
case mode.IsRegular():
return serve(path), nil
}
return "", nil
}
func serve(name string) string {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Set `no-cache` to flush the cache on Apple TV.
w.Header().Set("Cache-Control", "no-cache")
http.ServeFile(w, r, name)
})
l, err := util.Listen()
if err != nil {
log.Fatal(err)
}
go http.Serve(l, http.DefaultServeMux)
return fmt.Sprintf("http://%s", l.Addr().String())
}