forked from unlock-music/simple-server
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
58 lines (51 loc) · 1.22 KB
/
main.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
package main
import (
"embed"
"fmt"
"github.com/pkg/browser"
"io/fs"
"log"
"net/http"
"os"
"os/signal"
"path"
)
//go:generate go run ./builder
//go:embed build/for-build
var asset embed.FS
var listen = "localhost:8086"
func main() {
if tmp := os.Getenv("UM_LISTEN"); tmp != "" {
listen = tmp
}
pfxFs := WithPrefix(asset, "build/for-build")
go func() {
err := http.ListenAndServe(listen, http.FileServer(http.FS(pfxFs)))
if err != nil {
log.Println("启动出错,请检查是否有其他程序占用了端口:" + listen)
_, _ = fmt.Scanln()
log.Fatal(err)
}
}()
log.Printf("使用浏览器打开: %s 即可访问。", listen)
err := browser.OpenURL("http://" + listen)
if err != nil {
log.Println("自动打开浏览器错误,需要手动打开: "+listen, err)
}
sign := make(chan os.Signal, 1)
signal.Notify(sign, os.Interrupt, os.Kill)
<-sign
}
type WrappedFS struct {
inner fs.FS
prefix string
}
func (f WrappedFS) Open(p string) (fs.File, error) {
p = path.Join(f.prefix, p)
log.Printf("serving: %s\n", p)
return f.inner.Open(p)
}
// same thing but for ReadFile, Stat, ReadDir, Glob, and maybe Rename, OpenFile?
func WithPrefix(f fs.FS, p string) WrappedFS {
return WrappedFS{f, p}
}