Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions server.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"os"
"flag"
"log"

Expand All @@ -10,23 +11,39 @@ 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
)

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) {
fsHandler(ctx)
}

func createFsHandler(stripSlashes int) fasthttp.RequestHandler {
fs := &fasthttp.FS{
fs := &fasthttp.FS {
Root: *root,
Compress: *compress,
IndexNames: []string{"index.html"},
Expand All @@ -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 {
Expand Down