-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
  • 705
  • 10
  • 17
  • 1
    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
  • 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

1

Remove the / handler, and change the /mypath/ handler into 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 requested path. On your current /mypath handler, every request will be prefixed with /mypath/. Take a look at example below.

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

If the requested url path is not stripped, then (as per above example) it'll point into below respective locations, which is INVALID path and will result 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 into below locations, the correct one.

./my-project/dist/index.html
./my-project/dist/some/folder/style.css
...
novalagung
  • 9,699
  • 2
  • 50
  • 74