I am having some trouble serving some files from a subdirectory when a client request comes in at the root directory.
I am using gorilla/mux
to serve files. Here is my code below:
package main
import (
"log"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/zhughes3/zacharyhughes.com/configparser"
)
var config configparser.Configuration
func main() {
config := configparser.GetConfiguration()
r := mux.NewRouter()
initFileServer(r)
server := &http.Server{
Handler: r,
Addr: ":" + config.Server.Port,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(server.ListenAndServe())
}
func initFileServer(r *mux.Router) {
fs := http.FileServer(http.Dir("public/"))
r.PathPrefix("/public/").Handler(http.StripPrefix("/public/", fs))
}
The code that creates the file system is in the initFileServer
function above.
Currently, it serves the static files as intended when the user goes to localhost:3000/public/
. However, I want the files to be served when the user goes to localhost:3000/
.
I tried changing the ParsePrefix function call to r.PathPrefix("/").Handler(http.StripPrefix("/public/", fs))
but it did not work. Any suggestions would be greatly appreciated...I am pretty new with Go.
Your file server is already serving files under /public
, so you don't need to strip the prefix from the http path. This should work:
r.PathPrefix("/").Handler(http.StripPrefix("/",fs))