This commit is contained in:
Piotr Biernat 2020-07-29 16:21:55 +02:00
commit f61736266d
6 changed files with 102 additions and 0 deletions

28
main.go Normal file
View File

@ -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")
}

4
modd.conf Normal file
View File

@ -0,0 +1,4 @@
**/*.go !**/*_test.go {
prep: go build -o server main.go server.go
daemon +sigterm: ./server -d public
}

View File

@ -0,0 +1 @@
No content in this file

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

1
public/someFile.html Normal file
View File

@ -0,0 +1 @@
<strong>No content in this file</strong>

68
server.go Normal file
View File

@ -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, "<a href=\""+fileURL+"\">"+file.Name()+"</a>")
}
response := strings.Join(outputDirList, "<br />")
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)
}