commit f61736266da333a43ae99e0f246f6a0c8dfdbc1d Author: Piotr Biernat Date: Wed Jul 29 16:21:55 2020 +0200 v0.5 diff --git a/main.go b/main.go new file mode 100644 index 0000000..a052a76 --- /dev/null +++ b/main.go @@ -0,0 +1,28 @@ +package main + +import ( + "flag" + "fmt" + "os" +) + +func main() { + var fdir string + flag.StringVar(&fdir, "d", "", "path to dir to serve") + flag.Parse() + + if fdir == "" { + printHelp() + os.Exit(0) + } + + s := Server{ + port: ":8080", + dirPath: fdir, + } + s.Serve() +} + +func printHelp() { + fmt.Println("Usage: -d path to dir to serve") +} diff --git a/modd.conf b/modd.conf new file mode 100644 index 0000000..3eca06b --- /dev/null +++ b/modd.conf @@ -0,0 +1,4 @@ +**/*.go !**/*_test.go { + prep: go build -o server main.go server.go + daemon +sigterm: ./server -d public +} \ No newline at end of file diff --git a/public/dir/otherFile.html b/public/dir/otherFile.html new file mode 100644 index 0000000..d4745c1 --- /dev/null +++ b/public/dir/otherFile.html @@ -0,0 +1 @@ +No content in this file \ No newline at end of file diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100644 index 0000000..8d22584 Binary files /dev/null and b/public/favicon.ico differ diff --git a/public/someFile.html b/public/someFile.html new file mode 100644 index 0000000..36ce7e5 --- /dev/null +++ b/public/someFile.html @@ -0,0 +1 @@ +No content in this file \ No newline at end of file diff --git a/server.go b/server.go new file mode 100644 index 0000000..f9f2d8f --- /dev/null +++ b/server.go @@ -0,0 +1,68 @@ +package main + +import ( + "io/ioutil" + "log" + "net/http" + "os" + "strings" +) + +// Server base struct +type Server struct { + port string + dirPath string +} + +func (s *Server) initHandler() { + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + path := s.dirPath + r.URL.Path + file, err := os.Lstat(path) + if err != nil { + log.Println("File " + path + " not exists") + http.NotFound(w, r) + return + } + + switch mode := file.Mode(); { + case mode.IsRegular(): + serveFile(w, r, path) + case mode.IsDir(): + serveDir(w, r, path) + } + }) + + log.Printf("Serving %v directory\n", s.dirPath) +} + +// Serve function +func (s *Server) Serve() { + s.initHandler() + + log.Print("Listening on", s.port) + log.Fatal(http.ListenAndServe(s.port, nil)) +} + +func serveDir(w http.ResponseWriter, r *http.Request, path string) { + log.Println("Serving " + path + " dir...") + dirList, err := ioutil.ReadDir(path) + if err != nil { + log.Fatalln(err) + return + } + + var outputDirList []string + for _, file := range dirList { + fileURL := strings.TrimRight(r.RequestURI, "/") + "/" + file.Name() + outputDirList = append(outputDirList, ""+file.Name()+"") + } + + response := strings.Join(outputDirList, "
") + w.Write([]byte(string(response))) +} + +func serveFile(w http.ResponseWriter, r *http.Request, path string) { + log.Println("Serving " + path + " file...") + + http.ServeFile(w, r, path) +}