如何使用Golang在非根路径上提供index.html

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)
}

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
...