main
 1package main
 2
 3import (
 4	"fmt"
 5	"log"
 6	"net/http"
 7	"os"
 8)
 9
10func host() string {
11	host := os.Getenv("HOST")
12	if host == "" {
13		return "localhost"
14	}
15	return host
16}
17
18func port() string {
19	host := os.Getenv("PORT")
20	if host == "" {
21		return "8080"
22	}
23	return host
24}
25
26func directory() string {
27	if len(os.Args) > 1 {
28		return os.Args[1]
29	}
30	return "."
31}
32
33func listenAddress() string {
34	return fmt.Sprintf("%s:%s", host(), port())
35}
36
37func buildHttpHandlerFor(root string) http.Handler {
38	http.Handle("/", http.FileServer(http.Dir(root)))
39
40	return http.HandlerFunc(
41		func(w http.ResponseWriter, r *http.Request) {
42			fmt.Printf("%s %s\n", r.Method, r.URL)
43			http.DefaultServeMux.ServeHTTP(w, r)
44		},
45	)
46}
47
48func startServer(address string, directory string) {
49	fmt.Printf("Listening and serving HTTP on http://%s\n", address)
50
51	log.Fatal(
52		http.ListenAndServe(
53			address,
54			buildHttpHandlerFor(directory),
55		),
56	)
57}
58
59func main() {
60	startServer(listenAddress(), directory())
61}