1

I want to serve my angular app index.html under localhost:3000/mypath/ is there a way to accomplish that?

package main

import (
    "net/http"
)

func main() {
    // This works
    http.Handle("/", http.FileServer(http.Dir("./my-project/dist/")))

    // This doesn't work, you get 404 page not found
    http.Handle("/mypath/", http.FileServer(http.Dir("./my-project/dist/")))
    http.ListenAndServe(":3000", nil)
}
user10714010
  • 865
  • 2
  • 13
  • 20
  • 3
    You'll have to use [`StripPrefix`](https://golang.org/pkg/net/http/#StripPrefix) since your index file lives in `"./my-project/dist/"` and not in `"./my-project/dist/mypath/"`. Example: https://golang.org/pkg/net/http/#example_FileServer_stripPrefix – mkopriva Jul 29 '19 at 06:37
  • 1
    Also see [Why do I need to use http.StripPrefix to access my static files?](https://stackoverflow.com/questions/27945310/why-do-i-need-to-use-http-stripprefix-to-access-my-static-files/27946132#27946132) – icza Jul 29 '19 at 07:57

1 Answers1

3

Remove the / handler, and change the /mypath/ handler into the code below:

http.Handle("/mypath/", http.StripPrefix("/mypath/", http.FileServer(http.Dir("./my-project/dist/"))))

The http.StripPrefix() function is used to remove the prefix of the requested path. On your current /mypath handler, every request will be prefixed with /mypath/. Take a look at the example below.

/mypath/index.html
/mypath/some/folder/style.css
...

If the requested URL path is not stripped, then (as per the above example) it'll point to the below respective locations, which is incorrect path, and will result in file not found error.

./my-project/dist/mypath/index.html
./my-project/dist/mypath/some/folder/style.css
...

By stripping the /mypath, it'll point to the below locations, the correct one.

./my-project/dist/index.html
./my-project/dist/some/folder/style.css
...
novalagung
  • 10,905
  • 4
  • 58
  • 82