Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

How to serve a Polymer Single-Page-Application with Go?

I am trying to serve the example Single Page Application built with Polymer (https://github.com/Polymer/polymer-starter-kit) with a Go server.

My directory layout is:

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

The contents of the static folder were auto-generated using the polymer CLI.

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

Where spaHandler and the rest of the code is taken from the Gorillamux recommended layout: https://github.com/gorilla/mux#serving-single-page-applications.

What happens when I go to localhost:8000 is that the title and favicon are correctly taken from the index.html, but the javascript application under src is not loaded:

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

That is not being loaded and it just displays a blank page.

Is this bad routing on the polymer-side or bad serving on the Go server?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
router.PathPrefix("/").Handler(http.StripPrefix("/",http.FileServer(http.Dir("./static/")

Replace static file path with this


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...