【问题标题】:Go with Gorilla Mux routing using Angular.js使用 Angular.js 使用 Gorilla Mux 路由
【发布时间】:2014-12-16 12:24:40
【问题描述】:

我似乎无法正确路由。我正在使用 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。

【问题讨论】:

  • 没有。它使客户端请求的每个在 gorilla 路由器中未定义的 URL 都响应 index.html 文件 - 从而让您的 angualr 应用程序处理 API 调用(ui-router、ngRoute)以外的路由:)。

标签: go routing mux gorilla


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

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

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

    router.PathPrefix("/{_:.*}").HandlerFunc(StaticFileServer)
    

    【讨论】:

      猜你喜欢
      • 2015-04-05
      • 1970-01-01
      • 2014-09-08
      • 2016-04-07
      • 2016-04-26
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 2015-04-18
      相关资源
      最近更新 更多