-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
63 lines (51 loc) · 1.15 KB
/
main.go
File metadata and controls
63 lines (51 loc) · 1.15 KB
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
package main
import (
"errors"
"flag"
"io/fs"
"log"
"mime"
"net/http"
"os"
"path"
)
var (
port = flag.String("p", "8100", "port to serve on")
directory = flag.String("d", ".", "the directory of static file to host")
encoding = flag.String("e", "", "encoding to use")
)
func main() {
flag.Parse()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
p := path.Join(*directory, r.URL.Path)
if r.URL.Path == "/" {
p = path.Join(*directory, "index.html")
}
w.Header().Add("Content-Type", mime.TypeByExtension(path.Ext(p)))
switch *encoding {
case "brotli":
if e, _ := exists(p + ".br"); e {
w.Header().Add("Content-Encoding", "br")
p = p + ".br"
}
case "gzip":
if e, _ := exists(p + ".gz"); e {
w.Header().Add("Content-Encoding", "gzip")
p = p + ".gz"
}
}
http.ServeFile(w, r, p)
})
log.Printf("Serving %s on HTTP port: %s\n", *directory, *port)
log.Fatal(http.ListenAndServe(":"+*port, nil))
}
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if errors.Is(err, fs.ErrNotExist) {
return false, nil
}
return false, err
}