1

I'm writing a Go Application that serves files in two different directories.

My project structure:

PROJECT_DIR
PROJECT_DIR/config
PROJECT_DIR/src
PROJECT_DIR/client
PROJECT_DIR/client/node_modules
PROJECT_DIR/client/www

in my main go file i start the file server using the following code:

func main() {
log.Print("started web server...");
httpsPortStr := ":" + strconv.FormatUint(config.CfgIni.HttpsPort, 10)
log.Printf("starting https web server at port %v", config.CfgIni.HttpsPort)
http.Handle("/", http.FileServer(http.Dir("client/www")))
http.Handle("/node_modules",http.FileServer(http.Dir(("client/node_modules"))))
err := http.ListenAndServeTLS(httpsPortStr, config.CfgIni.CertificateFile, config.CfgIni.PrivateKeyFile, nil)
if err != nil {
    log.Fatalf("https server stopped with the following error: %v", err)
} else {
    log.Print("https server stopped with no error")
}
}

as you can see I mapped / to client/www and /node_modules to client/node_modules.

when I try to access files on client/www for example https://host:port/test.html, it works great!

when I try to access files on client/node_modules for example: https://host:port/node_modules/test.html, I get 404 page not found.

test.html file exists in both location and is readable (no permission problems).

I'm probably configuring the routing wrong somehow.

any ideas?

thanks!

ufk
  • 30,912
  • 70
  • 235
  • 386

1 Answers1

1

The FileServer is trying to route paths such as /node_modules/... to the file "client/node_modules/node_modules/..."

So use StripPrefix, eg:

http.Handle("/node_modules", http.StripPrefix("/node_modules", http.FileServer(http.Dir(("client/node_modules")))))

See another answer here.

Community
  • 1
  • 1
Mark
  • 6,731
  • 1
  • 40
  • 38
  • thanks. i needed to provide the first parameter to http.Handle, the following value: "/node_modules/" (an ending / to the directory). now it works – ufk Jun 23 '16 at 04:40