0

我似乎无法正确路由。我正在使用 Gorilla Mux 并且我正在尝试从任何 url 提供我的 angular 应用程序,所以基本上是我的 index.html,除了它们以“/foo”开头。

这个有效:

func StaticFileServer(w http.ResponseWriter, r *http.Request) {
  http.ServeFile(w, r, config.dir)
}

func main() {

  fs := http.Dir(config.dir)
  fileHandler := http.FileServer(fs)

  router = mux.NewRouter()

  router.Handle("/foo/page", PublicHandler(handler(getAll)).Methods("GET")
  router.Handle("/foo/page/{id}", PublicHandler(handler(getOne)).Methods("GET")

  router.PathPrefix("/{blaah}/{blaah}/").Handler(fileHandler)
  router.PathPrefix("/").HandlerFunc(StaticFileServer)

  ...
}

但是必须有一种更简单的方法,而不是显式声明每条可能的路线,比如这个 PathPrefix("/{blaah}/{blaah}/") thingy... 有了这个,除 /{blaah}/{blaah 之外的任何其他 url }/ 返回未找到的 404 页面,而不是 index.html。

因此,只要可以找到所有内容(静态文件等),我都希望得到服务,但其他所有内容都应返回/public/index.html。

4

2 回答 2

1

我也面临同样的问题,但如果我们使用 Gorilla mux,我们有一个明确的解决方案。

因为 Angular 是一个单页应用程序,所以我们必须这样处理。我有两个文件夹客户端和服务器。在客户端文件夹中,我保留所有角度代码,在服务器文件夹中,我保留所有服务器代码,因此渲染 index.html 的静态路径是“client/dist”。这里的 dist 文件夹是一个有角度的构建文件夹。

Go路由器代码如下 -

 func main {
        router := mux.NewRouter()
        spa := spaHandler{staticPath: "client/dist", indexPath: "index.html"}
        router.PathPrefix("/").Handler(spa)
}

spaHandler 实现了 http.Handler 接口,因此我们可以使用它来响应 HTTP 请求。静态目录的路径和该静态目录中的索引文件的路径用于为给定静态目录中的 SPA 提供服务。

type spaHandler struct {
    staticPath string
    indexPath  string
}

ServeHTTP 检查 URL 路径以在 SPA 处理程序的静态目录中定位文件。如果找到一个文件,它将被提供。如果不是,则将提供位于 SPA 处理程序上的索引路径的文件。这是为 SPA(单页应用程序)提供服务的合适行为。

func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

    // get the absolute path to prevent directory traversal
    path, err := filepath.Abs(r.URL.Path)
    if err != nil {
        // if we failed to get the absolute path respond with a 400 bad request
        // and stop
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    // prepend the path with the path to the static directory
    path = filepath.Join(h.staticPath, path)

    // check whether a file exists at the given path
    _, err = os.Stat(path)
    if os.IsNotExist(err) {
        // file does not exist, serve index.html
        http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
        return
    } else if err != nil {
        // if we got an error (that wasn't that the file doesn't exist) stating the
        // file, return a 500 internal server error and stop
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    // otherwise, use http.FileServer to serve the static dir
    http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)
}
于 2020-05-19T21:01:14.380 回答
0

我有点晚了,但其他人可能会发现我的回答很有用。

基本上,Gorilla Mux 在这里完成所有的路由。我假设您希望 AngularJS 为任何不以“/foo”开头的 URL 进行路由。

您可以使用正则表达式将任何不以“/foo”开头的请求发送到您的 index.html,方法是:

router.PathPrefix("/{_:.*}").HandlerFunc(StaticFileServer)
于 2015-04-01T23:10:18.383 回答