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

cvxl0en2  于 2023-04-09  发布在  Go
关注(0)|答案(1)|浏览(132)

我想在localhost:3000/mypath/下为我的Angular 应用程序index.html提供服务,有没有办法实现这一点?

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

bgibtngc1#

删除/处理程序,并将/mypath/处理程序更改为以下代码:

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

http.StripPrefix()函数用于删除请求路径的前缀。在您当前的/mypath处理程序中,每个请求都将以/mypath/为前缀。请看下面的示例。

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

如果请求的URL路径没有被剥离,那么(按照上面的例子)它将指向下面的相应位置,这是错误的路径,并将导致file not found错误。

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

通过剥离/mypath,它将指向下面的位置,正确的位置。

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

相关问题