package main import ( "flag" "fmt" "log" "net" "net/http" "os" ) func accessLog(h http.Handler, quiet bool) http.Handler { t := &TemplateHandler{handler: h} fn := func(w http.ResponseWriter, r *http.Request) { if !quiet { log.Println(r.Method, r.URL.Path, r.RemoteAddr) } t.ServeHTTP(w, r) } return http.HandlerFunc(fn) } var _allow_upload bool // todo: inject as dependency func main() { ip_f := flag.String("ip", "0.0.0.0", "IP adress to listen on.") port_f := flag.String("port", "3000", "Port to listen on.") dir_f := flag.String("dir", ".", "Directory to serve.") disallow_upl_f := flag.Bool("disallow-upload", false, "Disallow uploads to /upload.") upl_dir_f := flag.String("upload-dir", ".", "Directory to store uploaded files.") quiet_f := flag.Bool("quiet", false, "Be quiet, suppress output.") flag.Parse() port := os.Getenv("PORT") if port == "" { port = *port_f } if !*quiet_f { fmt.Print("You started µhttpd listening on " + *ip_f + ":" + port + " serving \"" + *dir_f + "\" as content.") if !*disallow_upl_f { fmt.Println(" Upload is enabled and accessible under /upload.") } else { fmt.Println(" Upload is disabled.") } fmt.Print("To view open your browser and try to open this as a url: ") if *ip_f == "0.0.0.0" { addrs, err := net.InterfaceAddrs() if err != nil { log.Fatal(err) return } for cnt, adr := range addrs { if ipnet, ok := adr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipnet.IP.To4() != nil { if cnt > 1 { fmt.Printf(" or http://%s:%s/", ipnet.IP.String(), port) } else { fmt.Printf("http://%s:%s/", ipnet.IP.String(), port) } } } } } else { fmt.Print("http://" + *ip_f + ":" + port + "/") } fmt.Print("\n\n") } mux := http.NewServeMux() if !*disallow_upl_f { os.MkdirAll(*upl_dir_f, 0755) mux.Handle("/upload", uploadHandler(*upl_dir_f, *quiet_f)) _allow_upload = true } mux.Handle("/", accessLog(http.FileServer(http.Dir(*dir_f)), *quiet_f)) log.Fatal(http.ListenAndServe(*ip_f+":"+port, mux)) }