diff --git a/server.go b/server.go index 14566eb..d5380f9 100644 --- a/server.go +++ b/server.go @@ -1,6 +1,7 @@ package main import ( + "os" "flag" "log" @@ -10,6 +11,7 @@ import ( var ( addr = flag.String("h", "0.0.0.0:8080", "TCP address to listen to") root = flag.String("d", "/usr/share/httpd", "Directory to serve static files from") + file = flag.String("f", "index.html", "File to serve") strip = flag.Int("s", 0, "Number of mount point to skip") compress = flag.Bool("c", false, "Enables transparent response compression if set to true") fsHandler fasthttp.RequestHandler @@ -17,8 +19,23 @@ var ( func notFoundHandler(ctx *fasthttp.RequestCtx) { ctx.Logger().Printf("File %s not found, defaulting to index.html", ctx.Path()) - ctx.Request.SetRequestURI("/index.html") - fsHandler(ctx) + if isIndexFileExists() { + ctx.Request.SetRequestURI("/index.html") + fsHandler(ctx) + } else { + ctx.Error("Internal Server Error", fasthttp.StatusInternalServerError) + } +} + +func isIndexFileExists() bool { + path := *root + "/" + *file + if _, err := os.Stat(path); err != nil { + if os.IsNotExist(err) { + log.Printf("File %s do not exists", *file) + return false + } + } + return true } func requestHandler(ctx *fasthttp.RequestCtx) { @@ -26,7 +43,7 @@ func requestHandler(ctx *fasthttp.RequestCtx) { } func createFsHandler(stripSlashes int) fasthttp.RequestHandler { - fs := &fasthttp.FS{ + fs := &fasthttp.FS { Root: *root, Compress: *compress, IndexNames: []string{"index.html"}, @@ -45,7 +62,7 @@ func main() { fsHandler = createFsHandler(*strip) // Start HTTP server. - if len(*addr) > 0 { + if len(*addr) > 0 && isIndexFileExists() { log.Printf("Starting HTTP server on %q", *addr) log.Printf("Serving files from directory %q", *root) if err := fasthttp.ListenAndServe(*addr, requestHandler); err != nil {