-
Notifications
You must be signed in to change notification settings - Fork 0
/
serv.go
68 lines (58 loc) · 1.73 KB
/
serv.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
package main
import (
"encoding/json"
"flag"
"log"
"net/http"
"os"
)
func applyHeadersHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Cache-Control", "No-Cache")
h.ServeHTTP(w, r)
})
}
func registerHandlers(mux *http.ServeMux, paths map[string]string) {
var handler http.Handler
for pattern, root := range paths {
fileInfo, err := os.Stat(root)
if err != nil {
log.Println("Error: path doesn't exist: " + root)
} else {
if fileInfo.IsDir() {
log.Printf("Registering handler with pattern: %s, root path: %s",
pattern, root)
handler = applyHeadersHandler(http.FileServer(http.Dir(root)))
mux.Handle(pattern, http.StripPrefix(pattern, handler))
} else {
log.Printf("Registering handler with pattern: %s, file: %s",
pattern, root)
handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, root)
})
mux.Handle(pattern, applyHeadersHandler(handler))
}
}
}
}
func parsePaths(paths string) (pathMap map[string]string, err error) {
err = json.Unmarshal([]byte(paths), &pathMap)
return
}
func main() {
var listen = flag.String("listen", ":8080",
"Interface/port to listen on. eg. :8080 or 127.0.0.1:8080")
var pathsRaw = flag.String("paths", `{"/": "."}`,
"Paths to serve. A json object with the keys as the url pattern, and "+
"the value as the root. Default serves current folder.")
flag.Parse()
paths, err := parsePaths(*pathsRaw)
if err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
registerHandlers(mux, paths)
log.Println("Listening on: ", *listen)
log.Fatal(http.ListenAndServe(*listen, mux))
}