Skip to content

Commit 8316ed7

Browse files
committed
fix linters and improve tests
1 parent 5b991c2 commit 8316ed7

File tree

3 files changed

+10
-12
lines changed

3 files changed

+10
-12
lines changed

configs/.env

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
11
APP_NAME=static-server
2-
STATIC_DIR_PATH=
3-
FILE_NOT_FOUND_PATH=
2+
STATIC_DIR_PATH=

main.go

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,14 @@ import (
1010
)
1111

1212
const defaultStaticFilePath = `./static`
13-
const defaultPathFileNotFound = "/404.html"
13+
const indexHTML = "/index.html"
14+
const htmlExtension = ".html"
15+
const rootPath = "/"
1416

1517
func main() {
1618
app := gofr.New()
1719

1820
staticFilePath := app.Config.GetOrDefault("STATIC_DIR_PATH", defaultStaticFilePath)
19-
fileNotFoundPath := app.Config.GetOrDefault("FILE_NOT_FOUND_PATH", defaultPathFileNotFound)
2021

2122
app.UseMiddleware(func(_ http.Handler) http.Handler {
2223
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -25,20 +26,17 @@ func main() {
2526
// check if the path has a file extension
2627
ok, _ := regexp.MatchString(`\.\S+$`, filePath)
2728

28-
if r.URL.Path == "/" {
29-
filePath = "/index.html"
29+
if r.URL.Path == rootPath {
30+
filePath += indexHTML
3031
} else if !ok {
3132
if stat, err := os.Stat(filePath); err == nil && stat.IsDir() {
32-
filePath = filepath.Join(r.URL.Path, "/index.html")
33+
filePath += indexHTML
3334
} else {
34-
r.URL.Path += ".html"
35+
filePath += htmlExtension
3536
}
3637
}
3738

38-
filePath = filepath.Join(staticFilePath, r.URL.Path)
3939
if _, err := os.Stat(filePath); os.IsNotExist(err) {
40-
r.URL.Path = fileNotFoundPath
41-
4240
w.WriteHeader(http.StatusNotFound)
4341

4442
filePath = filepath.Join(staticFilePath, "404.html")

main_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,8 @@ func TestServer(t *testing.T) {
4747
}{
4848
{"/", http.StatusOK},
4949
{"/index", http.StatusOK},
50-
{"/index/", http.StatusNotFound},
50+
{"/index/", http.StatusOK},
51+
{tempDir + "/index.html", http.StatusNotFound},
5152
{"/index.html", http.StatusOK},
5253
{"/nonexistent", http.StatusNotFound},
5354
}

0 commit comments

Comments
 (0)