问题描述
我正在尝试使用 Go 服务器为使用 polymer (https://github.com/Polymer/polymer-starter-kit) 构建的示例单页应用程序提供服务。
我的目录布局是:
.
├─serve.go
├─static
├───images
├───node_modules
├───src
├───test
├───...
├───index.html
我的 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>
解决方法
router.PathPrefix("/").Handler(http.StripPrefix("/",http.FileServer(http.Dir("./static/")
用这个替换静态文件路径