Commit 9571773

mo khan <mo@mokhan.ca>
2021-09-05 19:20:53
feat: log requests and accept custom dir to serve tag: v0.2.0
1 parent 5c784dc
Changed files (1)
main.go
@@ -23,14 +23,39 @@ func port() string {
 	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 main() {
-	address := listenAddress()
-	fmt.Printf("HTTP Server Ready at http://%s\n", address)
+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("Starting Server...!\n\thttp://%s\n", address)
 
-	http.Handle("/", http.FileServer(http.Dir(".")))
-	log.Fatal(http.ListenAndServe(address, nil))
+	log.Fatal(
+		http.ListenAndServe(
+			address,
+			buildHttpHandlerFor(directory),
+		),
+	)
+}
+
+func main() {
+	startServer(listenAddress(), directory())
 }