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
|
package main
import (
"fmt"
"log"
"net/http"
"os"
)
func host() string {
host := os.Getenv("HOST")
if host == "" {
return "localhost"
}
return host
}
func port() string {
host := os.Getenv("PORT")
if host == "" {
return "8080"
}
return host
}
func directory() string {
if len(os.Args) > 1 {
return os.Args[1]
}
return "."
}
func listenAddress() string {
return fmt.Sprintf("%s:%s", host(), port())
}
func buildHttpHandlerFor(root string) http.Handler {
http.Handle("/", http.FileServer(http.Dir(root)))
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("%s %s\n", r.Method, r.URL)
http.DefaultServeMux.ServeHTTP(w, r)
},
)
}
func startServer(address string, directory string) {
fmt.Printf("Listening and serving HTTP on http://%s\n", address)
log.Fatal(
http.ListenAndServe(
address,
buildHttpHandlerFor(directory),
),
)
}
func main() {
startServer(listenAddress(), directory())
}
|