【问题标题】:How to serve a Polymer Single-Page-Application with Go?如何使用 Go 为聚合物单页应用程序提供服务?
【发布时间】:2021-04-07 02:17:13
【问题描述】:

我正在尝试通过 Go 服务器为使用 Polymer (https://github.com/Polymer/polymer-starter-kit) 构建的示例单页应用程序提供服务。

我的目录布局是:

.
├─serve.go
├─static
├───images
├───node_modules
├───src
├───test
├───...
├───index.html

静态文件夹的内容是使用聚合物 CLI 自动生成的。

我的serve.go:

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) {
        // an example API handler
        json.NewEncoder(w).Encode(map[string]bool{"ok": true})
    })

    spa := spaHandler{staticPath: "static", indexPath: "index.html"}
    router.PathPrefix("/").Handler(spa)

    srv := &http.Server{
        Handler: router,
        Addr:    "127.0.0.1:8000",
        // Good practice: enforce timeouts for servers you create!
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }

    log.Fatal(srv.ListenAndServe())
}

其中 spaHandler 和其余代码取自 Gorillamux 推荐的布局:https://github.com/gorilla/mux#serving-single-page-applications

我去localhost:8000的时候发生的是title和favicon是从index.html中正确获取的,但是src下的javascript应用没有加载:

  <!-- Load your application shell -->
  <script type="module" src="src/my-app.js"></script>

它没有被加载,它只是显示一个空白页。

这是聚合物端的错误路由还是 Go 服务器上的错误服务?

【问题讨论】:

    标签: go polymer gorilla


    【解决方案1】:
    router.PathPrefix("/").Handler(http.StripPrefix("/",http.FileServer(http.Dir("./static/")
    

    用这个替换静态文件路径

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-01
      • 2017-06-06
      • 2011-12-08
      • 2020-08-18
      • 1970-01-01
      • 2015-04-12
      相关资源
      最近更新 更多