【问题标题】:Go + Angular: loading base htmlGo + Angular:加载基础 html
【发布时间】:2014-10-17 18:32:19
【问题描述】:

我正在尝试使用 Angular 在 Go 中编写应用程序。我不确定我的概念是否正确,但基本上我应该提供一个简单的 html 来加载 angular 和应用程序(js)本身,然后其余部分由 ajax 请求处理。我不知道如何为每个路径上的每个非 ajax 请求提供 html 文件?我想使用 Gorilla mux,但不知道该怎么做。

这是正确的方向吗?

【问题讨论】:

    标签: angularjs go


    【解决方案1】:

    对于不是任何已知 url 的每个请求,您应该发送 index.html - 或您的基本 Angular 应用程序文件。

    Gorilla/mux 有一个 NotFoundHandler,它是所有其他路由都不匹配的处理程序。你可以为它分配你自己的处理程序:

    gorilla/mux 的解决方案是:

    func main() {
        r := mux.NewRouter()
        r.HandleFunc("/foo", fooHandler)
        r.NotFoundHandler = http.HandlerFunc(notFound)
        http.Handle("/", r)
    
    }
    

    而 notFound 是:

    func notFound(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "static/index.html")
    }
    

    假设您的基础文件位于 static/index.html :)。

    现在您的所有请求不是任何其他请求(因此,在该设置中 - 不是路由中定义的 ajax 调用)将提供带有 url 的索引文件,该 url 可由 ngRoute 或 ui-router 处理。

    【讨论】:

      【解决方案2】:
          //serve static files from a folder 'public' which should be in the same dir as the executable.
          http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
              w.Header().Set("Cache-Control", "no-cache")
              http.ServeFile(w, r, "public"+r.URL.Path)
          })
      

      这将尝试从公共目录中提供每个不匹配的 URL。希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-14
        • 1970-01-01
        • 2022-09-28
        • 1970-01-01
        • 2015-05-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多