diff options
| author | mo khan <mo@mokhan.ca> | 2021-09-05 13:20:53 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2021-09-05 13:20:53 -0600 |
| commit | 9571773b3a891b4d50f92d1f8a0e0717f5986ccd (patch) | |
| tree | 434ed4bc0809800bc3525a9227325e9689188b0b | |
| parent | 5c784dc139df0e11a394ca93fac066e4951e0a84 (diff) | |
feat: log requests and accept custom dir to servev0.2.0
| -rw-r--r-- | main.go | 35 |
1 files changed, 30 insertions, 5 deletions
@@ -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()) } |
