Search code examples
gohttpfileserver

Go http.FileServer gives unexpected 404 error


I'm trying to run two file servers, one of them serving index.html in the ui folder, and one other serving some other static files, like the code below:

package main

import (
    "log"
    "net/http"
)

func main() {
    srv := http.NewServeMux()

    // File server 1
    uiServer := http.FileServer(http.Dir("./ui"))
    srv.Handle("/", uiServer)

    // File server 2
    staticFilesServer := http.FileServer(http.Dir("./files"))
    srv.Handle("/files", staticFilesServer)

    if err := http.ListenAndServe(":8080", srv); err != nil {
        log.Fatal(err)
    }
}

Both fileServer objects are defined in the exact same way, and the first one (uiServer) works fine, but the second (staticFilesServer on localhost:8080/files), gives me 404.


I narrowed down the problem and removed the first one (working file server), just like the code below:

package main

import (
    "log"
    "net/http"
)

func main() {
    srv := http.NewServeMux()

    staticFilesServer := http.FileServer(http.Dir("./files"))
    srv.Handle("/files", staticFilesServer)

    if err := http.ListenAndServe(":8080", srv); err != nil {
        log.Fatal(err)
    }
}

But it still gives me 404 on the path localhost:8080/files


If I change handle path from /files to /, it works as expected, but that's not what i want, I just want to know is it even possible to serve on paths other than / and how can I achieve that.


Also, my folder structure:

|- main.go
|- ui
|--- index.html
|- files
|--- file1.txt
|--- file2.csv
|--- file3.img

Solution

  • I realized that http.Dir() and http.ServeMux.Handle() would have a relation, they actually sum up their paths, as show below:

    srv.Handle("/files/", http.FileServer(http.Dir("."))
    

    Code above serves everything inside ./files folder, not . (as written in Dir(".")) And it fixed my problem.