-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve.go
50 lines (38 loc) · 962 Bytes
/
serve.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
package main
import (
"fmt"
"log"
"net/http"
"os/exec"
"path/filepath"
)
type loggingResponseWriter struct {
http.ResponseWriter
}
func (w *loggingResponseWriter) WriteHeader(code int) {
log.Printf("%v", code)
w.ResponseWriter.WriteHeader(code)
}
func wrapHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
lw := &loggingResponseWriter{w}
log.Printf("%s %s", r.Method, r.URL)
handler.ServeHTTP(lw, r)
})
}
func runServe(dir string, port int) {
addr := fmt.Sprintf(":%v", port)
absPath, err := filepath.Abs(dir)
if err != nil {
panic(err)
}
log.Println("Listening on port", port)
log.Println("Serving", absPath)
defer openBrowser(addr)
log.Fatal(http.ListenAndServe(addr, wrapHandler(http.FileServer(http.Dir(absPath)))))
}
func openBrowser(url string) {
url = "http://" + url
log.Printf("Opening %v", url)
exec.Command("cmd", "/c", "start", url).Start()
}